⚡ Postgraduate entrance examination interview ⚡ Algorithm daily practice - longest palindrome substring

Posted by alsinha on Tue, 28 Dec 2021 12:36:31 +0100

subject

Give you a string s and find the longest palindrome substring in S.

Example 1:

Input: s = "babad"
Output:"bab"
Explanation:"aba" The same answer is in line with the meaning of 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
s Only numbers and letters (uppercase and lowercase)/(or in figures)
Number of passes 666,680 Number of submissions 1,909,975

A little thought

Students who have seen my series should know that my main purpose here is to tell you what I think. When I see this problem, I first think of the longest substring without repeated characters, which was solved by sliding window at that time. The forgotten little partner can go back and have a look.
But today's question is obviously useless. My initial idea is very simple. Everyone has done the question of judging the number of palindromes! Then each substring is judged to find the largest one, which is the method of violent enumeration. I looked at it. It is OK to require 1 < = s.length < = 1000. So violent enumeration may timeout. I mean, maybe I didn't try. If you're interested, you can try

Don't say I'm lazy. Maybe not, so what method is used to solve this problem? Please see the following explanation.

Officially open

Determine palindrome string

Either way, we have to judge whether it is a palindrome string, so let's talk about this first. What is palindrome string? I won't say it myself.
Judgment method 1:

As shown in the figure, if the character pointed to by i is equal to the character pointed to by j, continue to move the two pointers inward, and then judge that one pair does not match, which is not the case for odd characters, and the same is true for even numbers.

Judgment method 2:

If it is an odd number, we will start from the middle character. If it is an even number, we will start from the middle two characters to judge whether the characters at the positions of i and j are equal. If they are not equal, it is not.
You can try to write these two methods according to your own ideas.

My problem solving method

Inspired by the second judgment method, a solution called central diffusion method is found. This judgment idea is almost the same, that is, the boundary case is the case where the substring length is 1 or 2. We enumerate each boundary case and continue to expand from the corresponding substring to both sides. If the letters on both sides are the same, we can continue to expand, for example, from P(i+1,j-1)P(i+1,j − 1) to P(i,j)P(i,j); If the letters on both sides are different, we can stop expanding, because the substring after that can not be a palindrome string.
Write out the judgment method first:

public int expandAroundCenter(String s, int left, int right) {
		//Judge the boundary problem and whether the characters at the positions of i and j (here left and right) are equal. If one of these conditions is not satisfied, it will directly jump out of the loop
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            --left;
            ++right;
        }
        return right - left - 1;
    }

Look at the main function

public String longestPalindrome(String s) {
		//This is mainly luck card. Generally, we won't give you a character test. Of course, we still need to be careful
        if (s == null || s.length() < 1) {
            return ;
        }
        int fei = 0, xue = 0;
        //Spread from the first element of the string as the center
        for (int i = 0; i < s.length(); i++) {
            //Start with odd substrings
            int len1 = expandAroundCenter(s, i, i);
            //On the premise of even substring
            int len2 = expandAroundCenter(s, i, i + 1);
            //Compare the two, who is bigger
            int len = Math.max(len1, len2);
            //Find the location of the new maximum palindrome string
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        //Returns this string
        return s.substring(fei, end + 1);
    }

About this method:

substring(int beginIndex, int endIndex)

Let's simply test the usefulness so that some big guys don't know. We can also try the method I said last time to learn more about it.

public static void main(String[] args) {
		String a="sfjls";
		System.out.println(a.substring(2,4));
		System.out.println(a.substring(2));
		
	}
result
jl
jls

Let's feel it. OK, that's all for today's algorithm. I'll see you tomorrow.

🎃 Special introduction:

📣 Xiaobai training column is suitable for newcomers who have just started. Welcome to subscribe Programming Xiaobai advanced
📣 If you don't understand anything, you are welcome to send a private letter or leave a message for detailed explanation. In addition, friends who want to advance can pay attention Training project column

📣 In addition, students who want to learn java web can take a look at this column: Teleporters
📣 It's an algorithm exercise for interview and postgraduate entrance examination. Let's cheer together The way ashore

Topics: Java Algorithm