题目:
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”
思路:
从中间向两边扫描
代码:
Java
public class Solution {
private int lo, maxLen;
public String longestPalindrome(String s) {
int len = s.length();
if (len < 2)
return s;
for (int i = 0; i < len-1; i++) {
extendPalindrome(s, i, i); //assume odd length, try to extend Palindrome as possible
extendPalindrome(s, i, i+1); //assume even length.
}
return s.substring(lo, lo + maxLen);
}
private void extendPalindrome(String s, int j, int k) {
while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {
j--;
k++;
}
if (maxLen < k - j - 1) {
lo = j + 1;
maxLen = k - j - 1;
}
}}
DP
public String longestPalindrome(String s) {
boolean[][] flag = new boolean[s.length()][s.length()];
int maxlen = 0,start = 0;
for(int i = 0;i < s.length(); i++){
flag[i][i] = true;
maxlen = 1;
start = i;
}
for(int i = 0;i < s.length()-1; i++)
if(s.charAt(i)==s.charAt(i+1)){
flag[i][i+1] = true;
maxlen = 2;
start = i;
}
for(int len = 3; len<= s.length(); len++)
for(int i = 0;i < s.length()-len+1; i++){
int j = i+len-1;
if(s.charAt(i)==s.charAt(j)&&flag[i+1][j-1]==true){
flag[i][j] = true;
maxlen = len;
start = i;
}
}
return s.substring(start, start+maxlen);
}
c++
class Solution {
public:
string longestPalindrome(string s) {
if (s.empty()) return "";
if (s.size() == 1) return s;
int min_start = 0, max_len = 1;
for (int i = 0; i < s.size();) {
if (s.size() - i <= max_len / 2) break;
int j = i, k = i;
while (k < s.size()-1 && s[k+1] == s[k]) ++k; // Skip duplicate characters.
i = k+1;
while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand.
int new_len = k - j + 1;
if (new_len > max_len) { min_start = j; max_len = new_len; }
}
return s.substr(min_start, max_len);
}
};