leetcode—5th
最长回文子串
1.扩展中心法:回文字符串都是中心对称的,所以可以选择中心点来一步步扩展求得最长回文子串,时间复杂度O(n^2)
class Solution {
public String longestPalindrome(String s) {
int start = 0,end = 0;
for(int i = 0;i<s.length();i++){
int len1 = expendSolution(s,i,i);
int len2 = expendSolution(s,i,i+1);
int length = Math.max(len1,len2);
if(length > end - start){
start = i-(length-1)/2;
end = i+length/2;
}
}
return s.substring(start,end+1);
}
private int expendSolution(String s,int left,int right){
int L = left;
int R = right;
while(L>=0&&R<s.length()&&s.charAt(L)==s.charAt(R)){
L--;
R++;
}
return R-L-1;
}
}
2.未完待更新