[daily algorithm / brush through leetcode] 5 Longest palindrome substring (medium)

Time:2022-4-30

Click here to view more content related to algorithmic interview~

Title Description

Give you a strings, findsThe longest palindrome substring in.

Example 1:

Input: S = “babad” output: “bab”

Explanation: “ABA” is also the answer to the question.

Example 2:

Input: S = “CBBD” output: “BB”

Example 3:

Input: S = “a” output: “a”

Example 4:

Input: S = “AC” output: “a”

Tips:

  • 1 <= s.length <= 1000
  • sIt consists only of numbers and English letters (uppercase and / or lowercase)

Simple solution

There is a simple way to solve this problem: enumerating stringssEach bit in the palindrome string, as the central point of the palindrome string, expands left and right until it reaches the boundary or does not meet the palindrome string definition.

The idea of doing so must be correct.

But obviously this is a simple (violent) approach, so how do we determine whether this approach is feasible?

Do you remember the analysis idea in our last section? In [brush through leetcode] 4 Among the difficulties in finding the median of two positively ordered arrays, I introduced to you that when we have a simple implementation method, we need to start fromData scale of the topicProcessing speed of computerandCalculation amount of implementation methodStart and judge whether such an approach will not time out.

Since the string length is only 1000 at most, and our implementation method is O (n ^ 2), the computation of our algorithm should be within 10 ^ 6, which is within the processing range of the computer per second.

First enumerate the center I of the palindrome string, and then extend the boundary to both sides in two cases until the boundary is reached or the palindrome string definition is not met:

  • If the length of palindrome string is odd, it shall be judged in turns[i − k] == s[i + k], k = 1,2,3…
  • If the length of palindrome string is even, it shall be judged in turns[i − k] == s[i + k − 1], k = 1,2,3…
class Solution {
    public String longestPalindrome(String s) {
        String ans = "";
        for (int i = 0; i < s.length(); i++) {
            //Palindrome string is odd
            int l = i - 1, r = i + 1;
            String sub = getString(s, l, r);
            if (sub.length() > ans.length()) ans = sub;

            //Palindrome string is even
            l = i - 1;
            r = i + 1 - 1;
            sub = getString(s, l, r);
            if (sub.length() > ans.length()) ans = sub;
        }
        return ans;
    }
    String getString(String s, int l, int r) {
        while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
            l--;
            r++;
        }
        return s.substring(l + 1, r);
    }
}

Time complexity: enumerate firstsEach character in the palindrome string is used as the central point of the palindrome string, and then expands from the central point to the left and right, up to the boundary. Complexity is $o (n ^ 2)$

Space complexity: $o (1)$


Manacher algorithm

This is a relatively unpopular algorithm with a relatively single scope of use. It can only be used to solve the “palindrome string” problem.

Manacher is indeed the optimal solution of the palindrome string problem.

But even for all the “palindrome string” problems on leetcode, none of them can AC only through O (n) manacher algorithm.

Therefore, I will give the solution directly here (which can be used directly as a template), rather than discussing the specific implementation principle of the algorithm.

The manacher algorithm is long. In order to avoid the discussion of the parity problem of palindrome string length, I will process the original characters and insert placeholders between the boundary and characters.

After using this technique,When the non placeholder character is used as the center of the palindrome string, it corresponds to the case that the length of the palindrome string is odd; When the placeholder character is used as the center of the palindrome string, it corresponds to the case that the length of the palindrome string is even.

for instance:

The original character: “babad”, after conversion: “* b * a * b * a * D *”, the resulting palindrome string: “* b * a * b *”, and then remove the placeholder to output: “bab”.

Explanation: “ABA” is also the answer to the question.

class Solution {
    public String longestPalindrome(String s) {
        if (s.length() == 1) return s;

        char[] chars = manacherString(s);
        int n = chars.length;
        int[] pArr = new int[n];
        int C = -1, R = -1, pos = -1;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            pArr[i] = i < R ? Math.min(pArr[C * 2 - i], R - i) : 1;
            while (i + pArr[i] < n && i - pArr[i] > -1) {
                if (chars[i + pArr[i]] == chars[i - pArr[i]]) {
                    pArr[i]++;
                } else {
                    break;
                }
            }
            if (i + pArr[i] > R) {
                R = i + pArr[i];
                C = i;
            }
            if (pArr[i] > max) {
                max = pArr[i];
                pos = i;
            }
        }
        int offset = pArr[pos];
        StringBuilder sb = new StringBuilder();
        for (int i = pos - offset + 1; i <= pos + offset - 1; i++) {
            if (chars[i] != '#') sb.append(chars[i]);
        }
        return sb.toString();
    }
    char[] manacherString(String s) {
        char[] chars = new char[s.length() * 2 + 1];
        for (int i = 0, idx = 0; i < chars.length; i++) {
            chars[i] = (i & 1) == 0 ? '#' : s.charAt(idx++);
        }
        return chars;
    }
}

Time complexity: the string is scanned only once. Complexity is $o (n)$

Space complexity: $o (1)$


summary

For today’s topic, Sanye not only provides a simple solution with a conventional time complexity of $o (n ^ 2) $, but also provides you with a template of manacher algorithm for the optimal solution of “palindrome string”. It is suggested that students with spare power can recite it.

The significance of reciting such an algorithm is that there is an API with a time complexity of $o (n) $in the brain. This API passes in a string and returns the maximum palindrome substring of the string.

At the same time, we also discuss the problem of “manacher’s length” and avoid the palindrome with the help of “manacher’s algorithm”.

For students who want to recite the manacher algorithm, it is recommended to type it three times and write it silently twice, and then write it twice after 24 hours. After a week, repeat it until they are proficient.

Don’t be afraid of forgetting. Forgetting is normal. More repetitions will form muscle memory. All the players who occupy the first page in the leetcode weekly competition are extremely skilled in algorithm routines and templates. Come on~


last

This is the third in our “brush through leetcode” seriesNo.5The series began on January 1, 2021. As of the start date, there are 1916 questions on leetcode, some of which are locked questions. We will finish all the unlocked questions first.

In this series of articles, in addition to explaining the problem-solving ideas, we will also give the most concise code as far as possible. If the general explanation is involved, the corresponding code template will also be.

Since leetcode’s questions are increasing with the weekly and biweekly competitions, in order to facilitate us to count the progress, we will calculate the progress according to the total number of questions at the beginning of the series as the denominator and the completed questions as the numerator. Current progress is5/1916

In order to facilitate the students to debug and submit code on the computer, I have established a relevant warehouse: GitHub address & gitee address.

In the warehouse address, you can see the problem solution link of the series of articles, the corresponding code of the series of articles, the original problem link of leetcode and some other preferred problem solutions.

Algorithm and data structure
Leetcode problem solving
Algorithmic interview