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"
方法一:Brute Force O(n^3)
想到了这个方法,但是觉得过不去time,就没有实现。这很不好,应该做到想到了就立刻写出来,跑一下看看。
这个版本是从Leetcode上面抄的。我原来自己写的版本果然超时了。不开森!
class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) return s;
int max = 1;
String ans = String.valueOf(s.charAt(0));
for(int i = 0; i < s.length(); i++){
for(int j = s.length() - 1; j > 0; j--){
int l = i;
int r = j;
if (max >= s.length() - i)
return ans;
while(l < r){
if (s.charAt(l) != s.charAt(r)) break;
else{
l++;
r--;
if (l >= r){
if (max < j-i+1){
max = j-i+1;
ans = s.substring(i,j+1);
}
}
}
}
}
}
return ans;
}
}
方法二:DP
class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) return s;
boolean[][] isPalindrome = new boolean[s.length()][s.length()];
for(int i = 0; i < s.length(); i++){
isPalindrome[i][i] = true;
for(int j = 0; j <= i; j++)
isPalindrome[i][j] = true;
}
int maxIndex = 0;
int minIndex = 0;
for(int i = s.length() - 1; i >= 0; i--){
for(int j = i + 1 ; j < s.length(); j++){
isPalindrome[i][j] = isPalindrome[i+1][j-1] && (s.charAt(i) == s.charAt(j));
if (isPalindrome[i][j] == true && (j - i > maxIndex - minIndex)){
minIndex = i;
maxIndex = j;
}
}
}
return s.substring(minIndex,maxIndex+1);
}
}
方法三:
明天再回来更新