LeetCode.5- palindromic longest substring (Longest Palindromic Substring)

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/codeMas/article/details/90746896

This is the first book of pleasure and delight 342 update, the first 366 Pian original

01 questions and look ready

LeetCode algorithm is introduced today in the Medium-level questions Question 3 (overall title No. 5). Given a string s, s to find the longest substring palindromic. You can assume that the maximum length of 1000 s. E.g:

Enter: "babad"
Output: "bab"
Note: "aba" is a valid answer.

Enter: "cbbd"
Output: "bb"

02 The first solution

Violent solution.
Taken two cycles using all substrings, determining whether the substring palindrome, which take the longest substring output as a result.
This complex solution time of Shi O(N^3)space complexity Shi O(1).

public String longestPalindrome(String s) {
    int max = 0, n = s.length();
    String result = "";
    for (int i=0; i<n; i++) {
        for (int j=i+1; j<=n; j++) {
            String tem = s.substring(i,j);
            if (isPalindrome(tem)) {
                if (j-i > max) {
                    max = j-i;
                    result = tem;
                }
            }    
        }
    }
    return result;
}

public boolean isPalindrome(String s){
    int left = 0, right = s.length()-1;
    while (left < right) {
        if (s.charAt(left) != s.charAt(right)) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

03 The second solution

We may also change a text way back into the left and right sides of the left and right sides of the intermediate to the intermediate.

Considerations in this palindrome length is odd or even, if it is an odd-shaped palindromic, with regard to the current character to find the center of both sides, e.g. palindromic "bab"; palindrome if the shape is an even number, the first two characters , and the two characters are equal, the current character and need to be adjacent the center character to find the left and right sides, e.g. palindromic "abba".

The time complexity of this solution is the O(N^2)space complexity Shi O(1).

public String longestPalindrome2(String s) {
    if (s.length() < 2) {
        return s;
    }
    int n = s.length(), start = 0, end = 0;
    for (int i=0; i<n-1; i++) {
        int len = helper(s, i, i);
        int len2 = helper(s, i, i+1);
        int len3 = Math.max(len, len2);
        if (len3 > end - start) {
            start = i - (len3-1)/2;
            end = i + len3/2;
        }
    }
    return s.substring(start, end+1);
}

/**
 * 以当前字符为中心向左右两边扩散,寻找回文子串
 * @param s 字符串
 * @param left 起始索引
 * @param right 结束索引
 * @return 回文子串长度
 */
public int helper(String s, int left, int right) {
    int n = s.length(), L = left, R = right;
    while (L >= 0 && R < n && s.charAt(L) == s.charAt(R)) {
        // 继续向左寻找
        L--;
        // 继续向右寻找
        R++;
    }
    return R - L -1;
}

04 A third solution

Dynamic programming algorithm, using space for time, is an improvement over the first solution.
The time complexity of this solution is the O(N^2)space complexity Shi O(N^2).

public String longestPalindrome3(String s) {
        if (s.length() < 2) {
            return s;
        }
        int n = s.length(), start = 0, end = 0;
        int maxLen = 0;
        // dp[j][i]表示子串[j,i]是回文
        boolean[][] dp = new boolean[n][n];
        // 右边界
        for (int i=0; i<n; i++) {
            // 左边界
            for (int j=i; j>=0; j--) {
                if (i == j) {
                    dp[j][i] = true;
                } else if (s.charAt(i) == s.charAt(j)) {
                    // 回文中至少3个字符
                    if (j < i-1) {
                        dp[j][i] = dp[j+1][i-1];
                    } else {
                        dp[j][i] = true;
                    }
                } else {
                    dp[i][j] = false;
                }
                // 比较最大值,并重新赋值
                if (i-j+1 > maxLen && dp[j][i]) {
                    maxLen = i-j+1;
                    start = j;
                    end = i;
                }
            }
        }
        return s.substring(start, end+1);
    }

05 The fourth solution

Horse-drawn vehicles algorithm (Manacher's Algorithm), from the forum, this is the first time I heard this algorithm, the time complexity is reduced to O(N), is very powerful, and subsequent take the time to learn more about this algorithm.

public String longestPalindrome4(String s) {
    String T = preProcess(s);
    int n = T.length();
    int[] P = new int[n];
    int C = 0, R = 0;
    for (int i = 1; i < n - 1; i++) {
        int i_mirror = 2 * C - i;
        if (R > i) {
            P[i] = Math.min(R - i, P[i_mirror]);
        } else {
            P[i] = 0;
        }
        while (T.charAt(i + 1 + P[i]) == T.charAt(i - 1 - P[i])) {
            P[i]++;
        }
        if (i + P[i] > R) {
            C = i;
            R = i + P[i];
        }
    }
    int maxLen = 0;
    int centerIndex = 0;
    for (int i = 1; i < n - 1; i++) {
        if (P[i] > maxLen) {
            maxLen = P[i];
            centerIndex = i;
        }
    }
    int start = (centerIndex - maxLen) / 2; 
    return s.substring(start, start + maxLen);
}

/**
 * 
 * @param s
 * @return
 */
public String preProcess(String s) {
    int n = s.length();
    if (n == 0) {
        return "^$";
    }
    String ret = "^";
    for (int i = 0; i < n; i++) {
        ret += "#" + s.charAt(i);
    }
    ret += "#$";
    return ret;
}

06 Summary

Thematic algorithm has been continuous days more than six months , the algorithm of feature articles 211 + articles, public Number dialog box reply [ data structures and algorithms ], [ algorithm ], [ data structures either] in a keyword, to obtain a series of articles Collection .

That's all, if you have any good solution ideas, suggestions or other issues, you can exchange comments below, thumbs up, message forwarding and support is the greatest reward for me!

Guess you like

Origin blog.csdn.net/codeMas/article/details/90746896