leetcode 647:回文子串的个数
题目描述:给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
解题步骤:这个题与求最长回文子串类似,只需要将每个子串是否为回文求出来在判断,通过动态规划求解
代码:
public int longestPalindrome(String s) {
int n = s.length();
int count = 0;
boolean[][] dp = new boolean[n][n];
for (int i = n-1; i >= 0; i--) {
dp[i][i] = true;
for (int j = i; j < n; j++) {
if(s.charAt(i) == s.charAt(j)) {
dp[i][j] = true&&(j-i<3||dp[i+1][j-1]);
if(dp[i][j])
count++;
}
else {
dp[i][j] = false;
}
}
}
for (int i = 0; i < dp.length; i++) {
System.out.println(Arrays.toString(dp[i]));
}
return count;
}