首页 > 代码库 > [leetcode]Longest Palindromic Substring

[leetcode]Longest Palindromic Substring

问题描述:

Given a string S, find the longest palindromic substring inS. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

基本思想:

本题的navie解法是对每个(i,j) i<=j 测试是否是回文串,并记录最大的情况。O(n^3)

如果从回文串的中心考虑往两边找,则只需要O(n^2)的复杂度。此方法就是将每个点作为回文串中心去判定,记录并保持最长的回文字串。为了处理方便,可以在字符串中每两个字符见插入一个特殊字符"#",这样就可以将偶数回文串和奇数回文串的处理形式统一起来。


代码:

   public String longestPalindrome(String s) {  //Java
        if(s.length() <= 1)
            return s;
            
        String tmpStr = "#";
        for(int i = 0; i <s.length(); i++)
            tmpStr += s.charAt(i) +"#";
        
        String max = "";
        for(int i = 1; i<tmpStr.length()-1; i=i+1){
            int toleft = i-1;
            int toright = i+1;
            while(toleft >=0 && toright <tmpStr.length()){
                if(tmpStr.charAt(toleft) != tmpStr.charAt(toright))
                    break;
                else {
                    toleft--;
                    toright++;
                }
            }
            if(toright - toleft -2 > max.length())
                max = tmpStr.substring(toleft+1,toright);
        }
        return max.replaceAll("#","");
    }


[leetcode]Longest Palindromic Substring