Palindromic Substrings Leetcode


#1

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.

#2

The below code expands at every index to calculate the no of palindromic substrings that exist in the string.

class Solution {
    public int countSubstrings(String s) {
        int result = 0;
        for(int i=0;i<s.length();i++){
            result += expand(s, i, i) + expand(s, i, i+1);
        }
        return result;
    }
    
    private int expand(String s, int i, int j){
        if(i<0 || j<0 || i>=s.length() || j>=s.length()) return 0;
        int count = 0;
        while(i>=0 && j<=s.length()-1){
            if(s.charAt(i--)==s.charAt(j++))
                count++;
            else
                break;
        }
        return count;
    }
}