647. 回文子串
难度:中等
2020/8/19每日一题打卡
题目描述
解题思路
1、动态规划法
定义的状态就是 dp[i][j]表示从i-j这个是不是回文
对于长度是一个字符的直接是回文,两个字符的话就比较是不是相等
对于两个以上,就看中间部分能不能组成回文串,然后比较两边是不是相等
dp[i][j] = dp[i+1][j-1] && dp[i] == dp[j],要用到右边的,所以第一层循环反着遍历
/*
* 647. 回文子串
* 2020/8/19
*/
public int countSubstrings(String s) {
char[] str = s.toCharArray();
int n = s.length();
boolean[][] dp = new boolean[n][n]; //dp[i][j]表示从i-j这个是不是回文
int count = 0;
//dp[i][j] = dp[i+1][j-1] && dp[i] == dp[j],要用到右边的,所以第一层循环反着遍历
for (int i = n-1; i >= 0; i--) {
for (int j = i; j < n; j++) {
if(i == j) {
dp[i][j] = true;
count++;
}else if(j - i == 1 && str[i] == str[j]){ //如果长度为2,比较字母是否相等
dp[i][j] = true;
count++;
}else if(j - i > 1 && str[i] == str[j] && dp[i+1][j-1]){
dp[i][j] = true;
count++;
}
}
}
return count;
}
2、中心拓展法
还有一种常见的判断回文子串的方法,就是中心拓展法,以每一个位置为中心,想两边拓展,看能得到多少合法的回文子串
//中心拓展法
public int countSubstrings(String s) {
char[] str = s.toCharArray();
int count = 0;
for (int i = 0; i < str.length; i++) {
count += isOk(str, i, i); //奇数
count += isOk(str, i, i+1); //偶数
}
return count;
}
public int isOk(char[] str,int p,int q) {
int re = 0;
while(p >= 0 && q < str.length) {
if(str[p] == str[q]) {
p--;q++;
re++;
}else {
break;
}
}
return re;
}