public class huiwen {
//判断字符串s[i...j]是否为回文串——dp O(n²)
public static boolean[][] isPailn(String str) {
boolean[][] mat = new boolean[str.length()][str.length()];
for (int i = str.length() - 1; i >= 0; i--) {
for (int j = i; j < str.length(); j++) {
if (j == i) {
//单字符为回文字符串
mat[i][j] = true;
} else if (j == i + 1) {
//相邻字符若相同则为回文字符串
mat[i][j] = (str.charAt(i) == str.charAt(j));
} else {
mat[i][j] = (str.charAt(i) == str.charAt(j)) && mat[i + 1][j - 1];
}
}
}
return mat;
}
}
判断字符串s[i...j]是否为回文串——动态规划
最新推荐文章于 2024-05-05 13:34:17 发布
该博客介绍了一个Java方法,用于判断给定字符串是否为回文串。通过使用动态规划,该方法的时间复杂度为O(n²)。博主详细解释了代码逻辑,包括初始化二维布尔数组、处理边界条件以及如何根据子问题构建全局解。
1372

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



