- 最长回文子串
给你一个字符串 s,找到 s 中最长的回文子串。
示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。
示例 2:
输入:s = “cbbd”
输出:“bb”
示例 3:
输入:s = “a”
输出:“a”
示例 4:
输入:s = “ac”
输出:“a”
双指针:
int st, end;
public String longestPalindrome(String s) {
int len = s.length();
if (len <= 1) return s;
char[] chars = s.toCharArray();
for (int i = 0; i < len; i++) {
helper(chars, i, i);
helper(chars, i, i + 1);
}
return s.substring(st, end + 1);
}
private void helper(char[] chars, int l, int r) {
while (l >= 0 && r < chars.length && chars[l] == chars[r]) {
--l;
++r;
}
if (end - st <= r - l ) {
st = l + 1;
end = r - 1;
}
}
动态规划:
def longestPalindrome(self, s: str) -> str:
size = len(s)
if size < 2:
return s
dp = [ [False for _ in range(size)] for _ in range(size) ]
max_len = 1
start = 0
for j in range(1, size):
dp[j][j] = True
for i in range(0, j):
dp[i][j] = (s[i] == s[j]) and (j - i < 3 or dp[i + 1][j - 1]) #java里用 && ||
if dp[i][j]:
cur_len = j - i + 1
if cur_len > max_len:
max_len = cur_len
start = i
return s[start:start + max_len]