Blind 75

Palindromic Substrings

Problem
LC 647
Category
String
File
blind75_LC647PalindromicSubstrings.java
Path
pkg5leetcode/blind75/blind75_LC647PalindromicSubstrings.java
Package
pkg5leetcode.blind75
Command
java pkg5leetcode/blind75/blind75_LC647PalindromicSubstrings.java
Approach
Expand around each center counting palindromes.
Complexity
Time O(n^2), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/blind75/blind75_LC647PalindromicSubstrings.java
1package pkg5leetcode.blind75;2 3/*4 * Palindromic Substrings | LC 6475 * APPROACH: Expand around each center counting palindromes.6 * COMPLEXITY: Time O(n^2), Space O(1)7 */8public class blind75_LC647PalindromicSubstrings {9    static int countSubstrings(String s) {10        int count = 0;11        for (int i = 0; i < s.length(); i++) {12            count += expand(s, i, i);13            count += expand(s, i, i + 1);14        }15        return count;16    }17 18    static int expand(String s, int lo, int hi) {19        int c = 0;20        while (lo >= 0 && hi < s.length() && s.charAt(lo) == s.charAt(hi)) { lo--; hi++; c++; }21        return c;22    }23 24    public static void main(String[] args) {25        check(countSubstrings("abc") == 3, "case1");26        check(countSubstrings("aaa") == 6, "case2");27        System.out.println("all tests passed");28    }29 30    static void check(boolean cond, String name) {31        if (!cond) throw new AssertionError("FAILED: " + name);32        System.out.println("  PASS " + name);33    }34}