Sunday, February 9, 2014

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.

Solution:
first try: check each pair of positions. TLE..
second try:



public class Solution {
    public String longestPalindrome(String s) {
        int len = s.length();
        if (len == 0) return "";
        String ret = s.substring(0,1);
        for(int i = 0; i <= len - 2; i++){
            String s1 = helper(s, i ,i);
            if(s1.length() > ret.length()) ret = s1;
            String s2 = helper(s, i ,i+1);
            if(s2.length() > ret.length()) ret = s2;
        }
        return ret;
    }
    public String helper(String tmp, int left, int right){
        char[] c = tmp.toCharArray();
        while(left >= 0 && right <= c.length-1 && c[left] == c[right]){
            left--;
            right++;
        }
        return tmp.substring(left+1, right);
    }
}

No comments:

Post a Comment