public String longestPalindrome(String s) {
if(s==null || s.length()<=1) return s;
int maxL=0;
int start=0;
for(int i=0; i<s.length();i++){
if(helper(s,i,i)>maxL){
maxL=helper(s,i,i);
start=i-maxL/2;
}
if((i!=0)&&(helper(s,i-1,i)>maxL)){
maxL=helper(s,i-1,i);
start=i-maxL/2;
}
}
return s.substring(start,start+maxL);
}
public int helper(String s, int i, int j){
while(i>=0 && j<s.length() && s.charAt(i)==s.charAt(j)){
i--;
j++;
}
return j-i-1;
}
Let's snipe the Leetcode problems together. No more hiding! Leetcode solution in Java! Your comments and suggestions are welcome!
Thursday, May 4, 2017
LeetCode 2nd time 5. Longest Palindromic Substring Leetcode Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment