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.
解释:这道题的关键是要遍历所有可能的结果。比如输入为:abc 需要遍历 (a,a)(a,b)(b,b)(b,c)(a,c)(c,c)(a,b,c),很明显只有三种是回文字符串。
方法一:中心遍历法
class Solution { private int cnt=0; public int countSubstrings(String s) { for(int i=0;i<s.length();i++){ extendSubString(s,i,i); extendSubString(s,i,i+1); } return cnt; } private void extendSubString(String s,int start,int end){ while(start>=0 && end<s.length() && s.charAt(start)==s.charAt(end)){ start--; end++; cnt++; } } }
方法二:动态规划
公式:dp[i]=dp[i-1]+tmp;
dp[i]表示回文数总数。tmp是每趟的回文数。
class Solution { private boolean ifPalindromic(String s){ for(int i=0;i<s.length()/2;i++){ if(s.charAt(i)!=s.charAt(s.length()-1-i)){ return false; } } return true; } public int countSubstrings(String s) { int N=s.length(); int [] dp=new int[N]; dp[0]=1; int tmp=0; for(int i=1;i<N;i++){ tmp=0; for(int j=0;j<=i;j++){ String tempString=s.substring(j,i+1); if(s.charAt(i)==s.charAt(j) && ifPalindromic(tempString)){ tmp++; } } dp[i]=dp[i-1]+tmp; } return dp[N-1]; } }