題目描述
給定一個字符串 s,找到 s 中最長的迴文子串。你可以假設 s 的最大長度爲 1000。
示例 1:
輸入: “babad”
輸出: “bab”注意: “aba” 也是一個有效答案。
示例 2:
輸入: “cbbd”
輸出: “bb”
思路分析
迴文串問題的核心是,從中間向兩邊擴散來判斷迴文串。每次傳入left和right兩個指針,所指元素相同就left- -,right++,直到不相同,返回(left+1,right)子串。
當然這屬於O(N^2)的解法,更巧妙的是馬拉車算法。詳情見左神算法進階班第一期。
代碼實現
public String longestPalindrome(String s) {
String res = "";
for (int i = 0; i < s.length(); i++) {
String s1 = strVaild(s, i, i);
String s2 = strVaild(s, i, i + 1);
res = res.length() > s1.length() ? res : s1;
res = res.length() > s2.length() ? res : s2;
}
return res;
}
//從中間往外走
public static String strVaild(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return s.substring(left + 1, right);
}