Palindromic Substrings

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:

Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".

 

Example 2:

Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

 

Note:

  1. The input string length won't exceed 1000.

brute force:

class Solution {
    public int countSubstrings(String s) {
        int n = s.length();
        int count = 0;
        for (int i = 0; i < n; i ++) {
            int right = i + 1;
            while (right <= n) {
                String sub = s.substring(i, right);
                if (isP(sub)) {
                    count ++;
                }
                right ++;
            }
        }
        return count;
    }
    
    private boolean isP(String s) {
        if (s.length() == 0) return false;
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left ++;
            right --;
        }
        return true;
    }
}

class Solution {
    public int countSubstrings(String s) {
        int n = s.length();
        int count = 0;
        for (int i = 0; i < n; i ++) {
            count += extend(s, i, i); // odd
            count += extend(s, i, i + 1); // even
        }
        return count;
    }
    
    private int extend(String s, int start, int end) {
        int count = 0;
        while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) {
            count ++;
            start --;
            end ++;
        }
        return count;
    }
}