Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
給定一個字符串 s
,找到 s
中最長的迴文子串。你可以假設 s
的最大長度爲 1000。
事實上,只需使用恆定的空間,我們就可以在 O(n^2)O(n2) 的時間內解決這個問題。
我們觀察到迴文中心的兩側互爲鏡像。因此,迴文可以從它的中心展開,並且只有 2n−1 個這樣的中心。
你可能會問,爲什麼會是 2n−1 個,而不是 n 箇中心?原因在於所含字母數爲偶數的迴文的中心可以處於兩字母之間(例如 \textrm{“abba”}“abba” 的中心在兩個 \textrm{‘b’}‘b’ 之間)。
class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() < 1) return "";
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
private int expandAroundCenter(String s, int left, int right) {
int L = left, R = right;
while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
L--;
R++;
}
return R - L - 1;
}
}