Java arithmetic exercises - the longest palindromic substring

Topic Link

Title Description

Given a string s, s to find the longest substring palindromic. You can assume that the maximum length of 1000 s.

Example 1

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。

Example 2

输入: "cbbd"
输出: "bb"

Solution to a problem (center expansion algorithm)

public String longestPalindrome(String string) {
    if (null == string || string.length() < 1) return "";
    int start = 0, end = 0;
    int num1, num2, len;
    for (int i = 0; i < string.length(); i++) {
        num1 = getMaxLength(string, i, i);
        num2 = getMaxLength(string, i, i + 1);
        len = Math.max(num1, num2);
        if (len > end - start) {
            start = i - (len - 1) / 2;
            end = i + len / 2;
        }
    }
    return string.substring(start, end + 1);
}

public int getMaxLength(String s, int left, int right) {
    int L = left, R = right;
    while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
        L--;
        R++;
    }
    return R - L - 1;
}

Complexity Analysis

  • Time complexity: $ O (n ^ 2) $, since the outlay will extend palindromic O (n) time around the center, the total complexity is: $ O (n ^ 2) $

  • Space complexity: $ O (1) $

Notes

Center expansion method violence compared to some of the more rational, no blind loop, the boundary is more central in both cases diminishing to both sides of the comparison.
Another algorithm complexity is $ O (n) $ Manacher the algorithm, and other follow-up study on the supplemented.

Attached

Netease cloud - "Prodigal Son"

the above

Guess you like

Origin www.cnblogs.com/mxwbq/p/10938952.html