lintcode-medium-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.

 

Example

Given the string = "abcdzdcab", return "cdzdc".

Challenge

O(n2) time is acceptable. Can you do it in O(n) time.

 

n^2做法:

public class Solution {
    /**
     * @param s input string
     * @return the longest palindromic substring
     */
    public String longestPalindrome(String s) {
        // Write your code here
        if(s == null || s.length() == 0)
            return s;
        
        String result = s.substring(0, 1);
        
        for(int i = 1; i < s.length(); i++){
            int left = i;
            int right = i;
            
            while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
                left--;
                right++;
            }
            
            String temp = s.substring(left + 1, right);
            if(temp.length() > result.length())
                result = temp;
        }
        
        for(int i = 0; i < s.length(); i++){
            int left = i;
            int right = i + 1;
            
            while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
                left--;
                right++;
            }
            
            String temp = s.substring(left + 1, right);
            if(temp.length() > result.length())
                result = temp;
        }
        
        return result;
    }
}

 

posted @ 2016-03-29 12:47  哥布林工程师  阅读(145)  评论(0编辑  收藏  举报