LintCode - 最长回文子串(普通)

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:容易
要求:

给出一个字符串(假设长度最长为1000),求出它的最长回文子串,你可以假定只有一个满足条件的最长回文串。

样例

给出字符串 "abcdzdcab",它的最长回文子串为 "cdzdc"。

思路
O(n2) 时间复杂度

/**
     * @param s input string
     * @return the longest palindromic substring
     */
    public String longestPalindrome(String s) {
        if(s == null || s.trim().length() <= 1){
            return s;
        }        
        String result = null;
        for(int i = 0; i < s.length(); i++){
            for(int j = i + 2; j < s.length() + 1; j++){
                if(isPalindrome(s.substring(i,j))){
                    String tmp = s.substring(i,j);
                    if(result == null){
                        result = tmp;  
                    }else if(tmp.length() > result.length()){
                        result = tmp;
                    }
                }
            }
        }
        return result;
    }
    
    /**
     *  是否为回文
     */
    private boolean isPalindrome(String s){
        int left = 0;
        int right = s.length() - 1;
        while(left < right){
            if(s.charAt(left) == s.charAt(right)){
                left++;
                right--;
            }else{
                break;
            }
        }
        return right <= left;
    }

O(n) 时间复杂度

public String longestPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        
        int length = s.length();    
        int max = 0;
        String result = "";
        for(int i = 1; i <= 2 * length - 1; i++){
            int count = 1;
            while(i - count >= 0 && i + count <= 2 * length  && get(s, i - count) == get(s, i + count)){
                count++;
            }
            count--; // there will be one extra count for the outbound #
            if(count > max) {
                result = s.substring((i - count) / 2, (i + count) / 2);
                max = count;
            }
        }
        
        return result;
    }
    
    private char get(String s, int i) {
        if(i % 2 == 0)
            return '#';
        else 
            return s.charAt(i / 2);
    }

你可能感兴趣的:(LintCode - 最长回文子串(普通))