解題思路
題目是查找最長的迴文子串。
如果某個字符串是一個迴文串,那麼形式可能是cbabc,或cbaabc的形式,要找到最長的迴文子串,可以以某個字符a開始,區分長度是奇數還是偶數,向左右兩邊一直比較,直到找到不同的字符。找到的字符就是以a爲中心的最長迴文子串。這樣,只要遍歷字符串,找到每個字符爲中心的最長迴文子串,就可以得到最終結果了。
參考源碼
public class Solution {
private String maxString = "";
public String longestPalindrome(String s) {
char[] chars = s.toCharArray();
int length = chars.length;
for (int i = 0; i < length; i++) {
// find longest odd palindrome
findPalindrome(chars, length, i, 0);
// find longest even palindrome
findPalindrome(chars, length, i, 1);
}
return maxString;
}
private void findPalindrome(char[] chars, int length, int i, int shift) {
int left = i;
int right = i + shift;
while (left >= 0 && right < length && chars[left] == chars[right]) {
left--;
right++;
}
if (right - left - 1 > maxString.length()) {
maxString = new String(chars, left + 1, right - left - 1);
}
}
}