Question

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:

  • The input string length won’t exceed 1000.

Solutions

  • Method 1: O(n^2) => two sides insert values
    class Solution {
        private char[] arr;
        public int countSubstrings(String s) {
            arr = s.toCharArray();
            int sum = 0;
            for(int i = 0; i < arr.length; i++){
                sum += expand(i, i);
                sum += expand(i, i + 1);
            }
            return sum;
        }
        private int expand(int i, int j){
            int res = 0;
            while(i >= 0 && j < arr.length && arr[i--] == arr[j++]){
                res++;
            }
            return res;
        }
    }
    
  • Method 2: dp
    class Solution {
        public int countSubstrings(String s) {
            int len = s.length();
            boolean[][] dp = new boolean[len][len];
            int res = 0;
            for(int i = len - 1; i >= 0; i--){
                for(int j = i; j < len; j++){
                    dp[i][j] = (s.charAt(i) == s.charAt(j)) && (j - i < 3 || dp[i + 1][j - 1]);
                    if(dp[i][j]) res++;
                }
            }
            return res;
        }
    }
    

Reference

  1. Java DP solution based on longest palindromic substring