public class Test {
public static void main(String[] args) {
String s = "abbabb";
int l = s.length();
int[][] dp = new int[l][l];
//dp[i][j]是下标i到j的子串的最长回文子序列
int i = 0, j = 0;
while (i < l) {
dp[i][j] = 1;
i++;
j++;
}
for (i = l - 1; i >= 0; i--) {
for (j = l - 1; j > i; j--) {
dp[i][j] = find(s, i, j, dp);
}
}
System.out.println(dp[0][l - 1]);
}
static int find(String s, int l, int r, int[][] dp) {
//去掉下面一行代码,时间复杂度暴增
if (dp[l][r] != 0) return dp[l][r];
int length = 0;
while (l < r) {
if (s.charAt(l) == s.charAt(r)) {
l++;
r--;
length += 2;
} else {
length += Math.max(find(s, l + 1, r, dp), find(s, l, r - 1, dp));
break;
}
}
return length;
}
}
最长回文子序列
最新推荐文章于 2024-09-07 16:56:49 发布