Thursday, May 4, 2017

LeetCode 2nd time 5. Longest Palindromic Substring Leetcode Java

   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;  
   }  

No comments:

Post a Comment