java获取最长回文子串
时间: 2023-08-14 19:07:17 浏览: 102
要获取最长回文子串,可以使用动态规划的方法来解决。下面是一个Java代码示例:
```java
public class LongestPalindrome {
public String longestPalindrome(String s) {
int n = s.length();
boolean[][] dp = new boolean[n][n];
int maxLength = 1;
int start = 0;
// 初始化单个字符为回文
for (int i = 0; i < n; i++) {
dp[i][i] = true;
}
// 判断长度为2的子串是否为回文
for (int i = 0; i < n - 1; i++) {
if (s.charAt(i) == s.charAt(i + 1)) {
dp[i][i + 1] = true;
start = i;
maxLength = 2;
}
}
// 判断长度大于2的子串是否为回文
for (int len = 3; len <= n; len++) {
for (int i = 0; i < n - len + 1; i++) {
int j = i + len - 1;
if (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]) {
dp[i][j] = true;
start = i;
maxLength = len;
}
}
}
return s.substring(start, start + maxLength);
}
public static void main(String[] args) {
阅读全文