Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad". Output: "bab". Note: "aba" is also a valid answer.
Input: "cbbd". Output: "bb".
Solution1:依次作为中心点向两边Extend
思路:遍历字符串s以不同的起点i,向两边extend并对称比较看是否为Palindrome,更新最大长度,并记录longest_palindrome起始位置start以便返回结果。
Time Complexity: O(N^2)
Space Complexity: O(1)
Runtime: 18ms
Example:
w t [ a b c c b a ] g x
<--(i)j k-->
Code:
public class Solution1 {
private int max_length;
private int start;
public String longestPalindrome(String s) {
if(s.length() < 2)
return s;
for(int i = 0; i < s.length(); i++) {
extendPalindrome2sides(s, i, i); // check the case when the palindrome length is odd
extendPalindrome2sides(s, i, i + 1); // check the case when the palindrome length is even
}
return s.substring(start, start + max_length);
}
private void extendPalindrome2sides(String s, int j, int k) {
while(j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) { // extend
j--;
k++;
}
int cur_leng = (--k) - (++j) + 1; // j, k step back
if(cur_leng > max_length) { // update
start = j;
max_length = cur_leng;
}
}
}
Solution1补充:
(1)考虑到奇数/偶数长度的Palindrome,这里作为两种case分别判断
(2)对于重复字符情况,如aaaaaaaaaa,i从第一个a开始extend后,已经能够知道后续重复很多a,然而再第二个a开始又需要再extend看一遍。
可见存在重复计算
Solution2:融合重复部分作为中心段 向两边Extend并 下次遍历可跳过此段
可以改善Solution1中提到的(1)(2)问题
思路:依次从i开始,如后面有与i后续重复的部分则融合一起作为中心段,再j、k分别从中心段的两端向外extend,下次的起始next_i则可以跳过当前的这个中心段。
此为case部分优化,时间/空间复杂度不变,Runtime: 11ms
Example:
next_i
w t [c b a a a a b c] g x
<--j i k-->
Code:
public class Solution2 {
private int max_length;
private int start;
public String longestPalindrome(String s) {
if(s.length() < 2)
return s;
for(int i = 0; i < s.length();) {
i = extendPalindrome2sides(s, i);
}
return s.substring(start, start + max_length);
}
private int extendPalindrome2sides(String s, int i) {
//if (s.length() - i <= max_length / 2) break; //[optional] corner case: no chance to surpass max_length
//Skip duplicate characters as Middle Part.
int j = i, k = i;
while(k < s.length() - 1 && s.charAt(k) == s.charAt(k + 1)) k++;
int next_i = k + 1;
//extend
while(j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {
j--;
k++;
}
// update
int cur_leng = (--k) - (++j) + 1;
if(cur_leng > max_length) {
start = j;
max_length = cur_leng;
}
return next_i;
}
}