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"
一上来我就想暴力过。。结果94个点只过了82个,算法自以为是O(n^2)实际上是O(n^3);
class Solution {
public String longestPalindrome(String s) {
int length = s.length();
int max = 1, j;
String string, result = s.substring(0,1);
for (int i = 0; i < length; i++){
j = length-1;
while (i < j){
while (s.charAt(j) != s.charAt(i)) j--;
string = s.substring(i,j+1);
if (palindromic(string) && max < string.length()){
max = string.length();
result = string;
}
j--;
}
}
return result;
}
private boolean palindromic(String string) {
int length = string.length();
int j;
for (int i = 0; i < length; i++){
j = length - i - 1;
if (string.charAt(i) != string.charAt(j)) return false;
}
return true;
}
}
答案算法O(n^2)
public String longestPalindrome(String s) {
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
private int expandAroundCenter(String s, int left, int right) {
int L = left, R = right;
while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
L--;
R++;
}
return R - L - 1;
}
很好理解不多说,我的思路是取一个字序列出来,再判断它是否为回文序列;
答案的思路是求以i为中心的最长回文子序列,回文子序列有两种“aba”和“abba”,因此有len1和len2;
substring(1,10)是从第一位截到第九位,第九位截进去而第十位不截
github