题目如下:
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.
最开始其实没想过到要用动态规划。最后往动态规划上靠了靠,还是很好理解的。
class Solution {
public boolean isPalindromic(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 dp[]=new int[s.length()];
for(int i=1;i<s.length();i++){
int temp=0;
for(int j=0;j<i;j++){//对于i以前的字符,遍历构建子串
if(s.charAt(j)==s.charAt(i)){
String tmpString=s.substring(j,i+1);//子串是从j到i
if(isPalindromic(tmpString)) temp++;//得到到i的所有子串的回文数量
}
}
dp[i]=dp[i-1]+temp;//动态规划
}
return dp[s.length()-1]+s.length();
}
}