Problem description: 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 static int countSubstrings(String s) { int num=0; int lens = s.length(); char[] ss = s.toCharArray(); int dp[][] = new int[lens][lens]; for(int i=0;i<lens;i++) { dp[i][i]=1; num++; } for(int i=0;i<lens-1;i++) { if(ss[i]==ss[i+1]) { dp[i][i+1] = 1; num++; } } for(int lenss=2;lenss<lens;lenss++) //对于超过三的子字符串,比较前后的字母;这里用到前面的结果。 for(int i=0;i<lens-lenss;i++){ //所以,时间复杂度大大降低了。 int j = i+lenss; if(dp[i+1][j-1]==1&&ss[i]==ss[j]) { dp[i][j] = 1; num++; } } return num; } }
本文介绍了一种算法,用于计算给定字符串中不同回文子串的数量。通过使用动态规划的方法,该算法能有效地区分不同起始和结束位置的子串,即使它们由相同的字符组成。
593

被折叠的 条评论
为什么被折叠?



