Saturday, January 10, 2015

Longest Palindromic Substring (LeetCode String)

Question: 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.

Idea: Start from each character i, grow the longest palindrome. The length of the palindromes may be odd (centered around i) or even length (centered around i,i+1).

Time: O(n^2) Space: O(1)

Code:
 public class Solution {  
   public String longestPalindrome(String s) {  
     if(s.length()<=1)  
       return s;  
     String result="";  
     for(int i=0;i<s.length();i++)  
     {  
       String tmp=expandFrom(i,i,s);  
       if(tmp.length()>result.length())  
         result=tmp;  
       tmp=expandFrom(i,i+1,s);  
       if(tmp.length()>result.length())  
         result=tmp;  
     }  
     return result;  
   }  
   public String expandFrom(int l,int r,String s)  
   {  
     while(l>=0&&r<s.length()&&s.charAt(l)==s.charAt(r))  
     {  
       l--;  
       r++;  
     }  
     return s.substring(l+1,r);  
   }  
 }  

No comments:

Post a Comment