题目链接
题目描述
给你一个字符串 s ,找到 s 中最长的回文子串。
示例 1:
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
示例 2:
输入:s = "cbbd"
输出:"bb"
示例 3:
输入:s = "a"
输出:"a"
示例 4:
输入:s = "ac"
输出:"a"
提示:
1 <= s.length <= 1000 s 仅由数字和英文字母(大写和/或小写)组成
解题思路
官方题解链接
代码(动态规划)
public String longestPalindrome(String s) {
if (s.length() < 2) {
return s;
}
int len = s.length();
boolean[][] dp = new boolean[len][len];
for (int i = 0; i < len; i++) {
dp[i][i] = true;
}
int begin = 0;
int maxLength = 1;
char[] chars = s.toCharArray();
for (int L = 2; L <= len; L++) {
for (int i = 0; i < len; i++) {
int j = i + L - 1;
if (j >= len) {
break;
}
if (chars[i] == chars[j]) {
if (j - i < 3) {
dp[i][j] = true;
} else {
dp[i][j] = dp[i + 1][j - 1];
}
}
if (dp[i][j] && j - i + 1 > maxLength) {
maxLength = j - i + 1;
begin = i;
}
}
}
return s.substring(begin,begin + maxLength);
}
复杂度
时间复杂度: O(n^2) 空间复杂度: O(n^2)
代码(中心扩展算法)
public String longestPalindrome(String s) {
if (s.length() < 1) {
return "";
}
int size = s.length();
int start = 0;
int end = 0;
for (int i = 0; i < size; i++) {
int len1 = expand(s, i, i);
int len2 = expand(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start + 1) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
int expand(String str, int left, int right) {
while (left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}
复杂度
时间复杂度: O(n^2) 空间复杂度: O(1)
|