Wednesday, January 7, 2015

LeetCode 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 s) {
        // Step 1: Find all of the center pairs, e.g, "axa" or "aa".
        // Step 2: For every pair, extendedly search the longest qualified range. Then return the longest one.
        int n = s.length();
        
        if (n <= 1)
            return s;
        
        int tmpLeft, tmpRight;
        int left, right;
        int maxLeft = 0, maxRight = 0;
        int max = 0;
        
        for (int i = 0; i < n-1; i++)
            for (int j = i+1; j<=i+2 && j<n; j++)
                if (s.charAt(i) == s.charAt(j))
                {
                    tmpLeft = i;
                    tmpRight = j;
                    left = i;
                    right = j;                    
                    
                    while (--tmpLeft>=0 && ++tmpRight<=n-1)
                        if (s.charAt(tmpLeft) == s.charAt(tmpRight))
                        {
                            left = tmpLeft;
                            right = tmpRight;
                        }
                        else
                            break;
                        
                    if (max < right-left+1)
                    {
                        max = right-left+1;
                        maxLeft = left;
                        maxRight = right;
                    }
                }
        
        return s.substring(maxLeft, maxRight+1);
    }
}

No comments:

Post a Comment