题目
给你一个字符串 s,找到 s 中最长的回文子串。
示例
示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。
示例 2:
输入:s = “cbbd”
输出:“bb”
示例 3:
输入:s = “a”
输出:“a”
示例 4:
输入:s = “ac”
输出:“a”
实现
暴力解法
class Solution {
public static void main(String[] args) {
String res = longestPalindrome("ac");
System.out.println(res);
}
public static String longestPalindrome(String s) {
char[] chars = s.toCharArray();
int maxLength = 0;
String res = "";
for (int i = 0; i < chars.length; i++) {
int left = i;
for (int j = chars.length - 1; j >= i; j--) {
int right = j;
while (left < right && chars[left] == chars[right]) {
left++;
right--;
}
if (right - left <= 0 && j - i + 1 > maxLength) {
maxLength = j - i + 1;
res = s.substring(i, j + 1);
}
}
}
return res;
}
}
动态规划
dp 方程
dp[i][j] 代表i到j是回文串
dp[i][i]=1;
if(s[i]==s[i+1]) dp[i][i+1]=1;
s[i]==s[i+len] && dp[i+1][i+len-1]==1 => do[i][i+len]=1
class Solution {
public static void main(String[] args) {
String res = longestPalindrome("mmacbca");
System.out.println(res);
}
public static String longestPalindrome(String s) {
int n = s.length();
int[] ans = new int[2];
boolean[][] dq = new boolean[n][n];
int max = 1;
//后一个指针
for (int i = 0; i < n; i++) {
//前一个指针
for (int j = 0; j < i; j++) {
dq[j][i] = (s.charAt(j) == s.charAt(i)) && (i - j < 3 || dq[j + 1][i - 1]);
if (dq[j][i] && max < i - j + 1) {
max = i - j + 1;
ans[0] = j;
ans[1] = i;
}
}
}
return s.substring(ans[0], ans[1] + 1);
}
}

249

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



