Description
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.
Example:
Input: "cbbd"
Output: "bb"
Solution
Iteration, O(n^2) time, O(1) space
更新winIndex十分容易出错,注意evenPalinLen = 0时winStart = i + 1, winEnd = i。
class Solution {
public String longestPalindrome(String s) {
if (null == s) {
return null;
}
int winStart = 0;
int winEnd = 0;
int len = s.length();
for (int i = 0; i < len; ++i) {
int oddPalinLen = extendPalindrome(s, i, i);
int evenPalinLen = extendPalindrome(s, i, i + 1);
if (oddPalinLen >= evenPalinLen && winEnd - winStart + 1 < oddPalinLen) {
winStart = i - (oddPalinLen - 1) / 2;
winEnd = i + (oddPalinLen - 1) / 2;
} else if (oddPalinLen < evenPalinLen && winEnd - winStart + 1 < evenPalinLen) {
winStart = i - evenPalinLen / 2 + 1; // important!
winEnd = i + evenPalinLen / 2 ;
}
}
return s.substring(winStart, winEnd + 1);
}
public int extendPalindrome(String s, int i, int j) {
while (i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j)) {
--i;
++j;
}
return j - i - 1;
}
}
DP, O(n^2) time, O(n) space
dp[i][j]表示s.substring(i, j + 1)是否为palindrome。
dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1])
注意i要从大往小计算!
class Solution {
public String longestPalindrome(String s) {
if (s == null) return null;
int len = s.length();
boolean[][] dp = new boolean[len][len];
int winStart = 0;
int winEnd = 0;
for (int i = len - 1; i >= 0; --i) { // important!
for (int j = i; j < len; ++j) {
dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);
if (dp[i][j] && j - i > winEnd - winStart) {
winStart = i;
winEnd = j;
}
}
}
return s.substring(winStart, winEnd + 1);
}
}
也可以按照step去DP,保证短的substring在长的substring之前就被处理完了。感觉这样的写法比上面这种更好理解。
class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() < 2) {
return s;
}
int n = s.length();
boolean[][] isPalindrome = new boolean[n][n];
int longestStart = 0;
int longestEnd = -1;
for (int step = 0; step < n; ++step) {
for (int i = 0; i < n - step; ++i) {
int j = i + step; // s.substring(i, j + 1)
if (s.charAt(i) == s.charAt(j) && (step < 3 || isPalindrome[i + 1][j - 1])) {
isPalindrome[i][j] = true;
if (step > longestEnd - longestStart) {
longestStart = i;
longestEnd = j;
}
}
}
}
return longestEnd == -1 ? "" : s.substring(longestStart, longestEnd + 1);
}
}