This is a "palindromic" problem, I think DP can solve this problem, but there is a easier way to solve it, the time complexity is O(n2):
private int res = 0; public int countSubstrings(String s) { for(int i=0;i<s.length();i++){ helper(s, i, i); // count the palindromic with odd number, eg. eabae helper(s, i, i+1); // count the palindromic with even number, eg. abba } return res; } private void helper(String s, int l, int r){ while(l>=0 && r<s.length()){ if(s.charAt(l)==s.charAt(r)){ res++; l--; r++; } else return; } }