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.
题解:大意就是找一个字符串中所有回文子串的个数。这里用动态规划,状态定义dp[i][j]表示字符串s[i]到s[j]的子串是否为回文,dp[i][j]=dp[i+1][j-1]&&s[i]==s[j] 从状态转移方程来开,只需要我们从下往上,从左往右遍历即可。
代码:
public static int countSubstrings(String s) {
if (s == null || s.length() <2)
return s.length()==1? 1: 0;
int n = s.length();
boolean[][] dp = new boolean[n][n];
for (int i = 0; i < n;i++)
{
dp[i][0] = true;
dp[n-1][i] =true;
}
int count = 2;
//字符串头尾两个单字符回文,即对角线上已经被初始化的两个
for (int i = n - 2; i >= 0; i--)
for (int j = 1; j < n; j++) {
if (i > j)
dp[i][j] = true;
else {
dp[i][j] = dp[i + 1][j - 1] && (s.charAt(i) == s.charAt(j));
count += dp[i][j] == true ? 1 : 0;
}
}
return count;
}
回文另一种解法:找中心点,然后往两边扩展判断是否相等,是否为回文。通过遍历以i为中心(奇数)或i和i+1(偶数),回文长度为奇数和偶数,遍历所有可能的中心点,查找回文的个数
int count = 0;
public int better_countSubstrings(String s) {
if (s == null || s.length() == 0) return 0;
for (int i = 0; i < s.length(); i++) { // i is the mid point
extendPalindrome(s, i, i); // odd length;
extendPalindrome(s, i, i + 1); // even length
}
return count;
}
private void extendPalindrome(String s, int left, int right) {
while (left >=0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
count++; left--; right++;
}
}
本文介绍了一种算法,用于找出给定字符串中所有的回文子串,并计算其总数。提供了两种方法:一种使用动态规划,另一种通过寻找中心点并向两侧扩展的方法。
3925

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



