Problem
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
Solution (Java)
class Solution {
public String longestPalindrome(String s) {
char[] newStr = new char[s.length() * 2 + 1];
newStr[0] = '#';
for (int i = 0; i < s.length(); i++) {
newStr[2 * i + 1] = s.charAt(i);
newStr[2 * i + 2] = '#';
}
int[] dp = new int[newStr.length];
int friendCenter = 0;
int friendRadius = 0;
int lpsCenter = 0;
int lpsRadius = 0;
for (int i = 0; i < newStr.length; i++) {
dp[i] =
friendCenter + friendRadius > i
? Math.min(dp[friendCenter * 2 - i], (friendCenter + friendRadius) - i)
: 1;
while (i + dp[i] < newStr.length
&& i - dp[i] >= 0
&& newStr[i + dp[i]] == newStr[i - dp[i]]) {
dp[i]++;
}
if (friendCenter + friendRadius < i + dp[i]) {
friendCenter = i;
friendRadius = dp[i];
}
if (lpsRadius < dp[i]) {
lpsCenter = i;
lpsRadius = dp[i];
}
}
return s.substring((lpsCenter - lpsRadius + 1) / 2, (lpsCenter + lpsRadius - 1) / 2);
}
}
Solution (Javascript)
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
var start = 0;
var end = 0;
var len = s.length;
var num = 0;
for (var i = 0; i < len; i++) {
num = Math.max(expandAroundCenter(s, i, i), expandAroundCenter(s, i, i + 1));
if (num > end - start) {
start = i - Math.floor((num - 1) / 2);
end = i + Math.floor(num / 2);
}
}
return s.slice(start, end + 1);
};
var expandAroundCenter = function (s, left, right) {
var l = left;
var r = right;
var len = s.length;
while (l >= 0 && r < len && s[l] === s[r]) {
l--;
r++;
}
return r - l - 1;
};
Explain:
遍历每个字符,检查以这个字符或相邻两个字符为中心是否回文,记录最长的回文字符位置。
Complexity:
- Time complexity : O(n^2).
- Space complexity : O(1).