Sunday, January 4, 2015

5. Longest Palindromic Substring Leetcode Java

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.

Solution:
Brute force method is very straightforward, check all possible substring of s if it is a palindromic substring and update the max length. Time complexity: O(n^3).

my solution:
Because of the specialty of palindromic string, we can pick the center of the substring, and find the longest palindromic substring based on this center.There are total l+l-1 centers in a string s with length l. For example s="baaba" if we chose the slot between 'a' and 'a' as the center,the longest palindromic substring is"baab", if we choose the 'b'(index 3) as the center, the longest palindromic substring for this center is"aba". So we can find the longest palindromic substring among all those palindromic substrings based on different centers.    
The time complexity is (2n-1)*n = O(n^2).


 public String longestPalindrome(String s) {  
     if(s==null || s.length()<2) return s;  
     int maxL=1;  
     int start=0;  
     for(int i=0;i<s.length()-1;i++){  
        int l1=helper(s,i,i+1);  
        if(l1>maxL) {  
          start=i-l1/2+1;  
          maxL=l1;  
        }  
        int l2=helper(s,i,i);  
        if(l2>maxL){  
          start=i-l2/2;  
          maxL=l2;  
        }  
     }  
     return s.substring(start,start+maxL);  
   }  
   public int helper(String s, int i, int j){  
     while(i>=0 && j<=s.length()-1 && s.charAt(i)==s.charAt(j)){  
         i--;  
         j++;  
     }  
     return j-i-1;  
   }  

No comments:

Post a Comment