您的位置:首页 > 其它

Leetcode no. 5

2016-04-23 16:49 351 查看
5. Longest Palindromic Substring

Given
a string S,
find the longest palindromic substring in S.
You may assume that the maximum length of S is
1000, and there exists one unique longest palindromic substring.

public class Solution {
public String longestPalindrome(String str) {
int start=0, end=0;
for (int i = 0; i < str.length(); i++) {
int len1= expand(str,i,i+1);
int len2= expand(str,i,i);
int len= (len1>len2) ? len1 : len2;
if (len>end-start){
start= i-(len-1)/2;
end= i+len/2;
}
}
return str.substring(start, end+1);
}

private int expand(String str, int left, int right){
int l=left, r=right;
while ( l>=0 && r<str.length() && str.charAt(l)==str.charAt(r)){
l--;
r++;
}
return r-l-1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: