最长回文字符串(Manacher Algorithm)

最长回文字符串问题:
(Leetcode Problem 5)
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
(给定一个字符串 s ,找出s中最长的回文子串,假定字符串s的最大长度为1000)
Example:
Input: “babad”
Output: “bab”
PS:【Note: “aba” is also a valid answer.】
Example:
Input: “cbbd”
Output: “bb”

Manacher Algorithm:

时间复杂度:O(n)
空间复杂度:O(n)

参考:https://segmentfault.com/a/1190000003914228

JAVA代码:

public class Solution {
    public String longestPalindrome(String s){

        /*Part1: 构建奇数个字符的字符串*/
        StringBuffer str = new StringBuffer("");
        str.append("$#");
        for(int x=0; xstr.append(s.charAt(x));
            str.append('#');
        }

        //System.out.println(str);
        /*Part2: 构建存储每个字符为轴的最长回文串的长度的数组*/
        int strArr[] = new int[str.length()];
        for(int x=0; x0;
        }

        /*Part3: 求数组*/
        int id = 0, mx = 0;        //id为子串的轴,mx为子串右最大边界
        for(int i=1; i<str.length(); i++){
            strArr[i] = mx > i ? Math .min(strArr[2*id-i],mx-i) : 1;
            while( i+strArr[i]0 && str.charAt(i+strArr[i]) == str.charAt(i-strArr[i])){
                strArr[i]++;
            }
            if(i+strArr[i]>mx){
                mx = i+strArr[i];
                id = i;
            }
        }
/*
        for(int x=0; x
        /*Part4: 计算最长回文子串的子串长度和子串的轴*/
        int max = strArr[0],loc = 0;
        for(int x=0; xif(strArr[x]>max){
                max = strArr[x];
                loc = x;
            }
        }

        //System.out.println(max);
        /*Part5: 构建最长回文子串*/
        StringBuffer sl = new StringBuffer(str.substring(loc-max+1, loc+max));
        for(int x=0; xif(sl.charAt(x)=='#'){
                sl.deleteCharAt(x);
            }
        }
        //System.out.println(sl);

        return new String(sl);

    }
}

你可能感兴趣的:(Leetcode)