今天是2020年5月21日,星期四。
題目描述
給定一個字符串 s,找到 s 中最長的迴文子串。你可以假設 s 的最大長度爲 1000。
示例 1:
輸入: "babad"
輸出: "bab"
注意: "aba" 也是一個有效答案。
示例 2:
輸入: "cbbd"
輸出: "bb"
題目思路
在本篇中,小編只介紹「中間擴展法」,其他方法大家可以在LeetCode題解區自取。
「中間擴展法」:從每一個位置出發,向左向右擴散。第一步,先驗證left、right位置的字符與當前字符是否相同,不斷變換left與right的值,直到left、right位置的字符與當前字符不同。第二步,比較left、right位置的字符是否相同,直到不同爲止。
在每次擴散的過程中,都會形成一個窗口,窗口大小爲len。如果當前的len > maxLen,則maxLen = len。因爲題目要求最終需要輸出最長的迴文串,所以需要記錄maxLen對應的迴文串的起始位置,即maxStartIndex = left。
參考代碼
class Solution {
public String longestPalindrome(String s) {
int length = s.length();
if (s == null || length == 0) {
return "";
}
int left = 0;
int right = 0;
int len = 1;
int maxStartIndex = 0;
int maxLen = 0;
for (int i = 0; i < length; i++) {
left = i - 1;
right = i + 1;
// 從當前中心向左側擴展,判斷是否left位置的字符與當前位置的字符相同
while (left >= 0 && s.charAt(left) == s.charAt(i)) {
left--;
len++;
}
// 從當前中心向右側擴展,判斷是否right位置的字符與當前位置的字符相同
while (right < length && s.charAt(right) == s.charAt(i)) {
right++;
len++;
}
// 上面兩個循環處理掉了與當前位置字符相同的字符,然後處理left與right位置上字符相同的情況
while (left >= 0 && right < length && s.charAt(right) == s.charAt(left)) {
left--;
right++;
len = len + 2;
}
if (len > maxLen) {
maxLen = len;
maxStartIndex = left;
}
len = 1;
}
return s.substring(maxStartIndex + 1, maxStartIndex + maxLen + 1);
}
}