LeetCode's longest palindrome string (409), longest palindrome substring (5), palindrome substring (647), counting binary substring (696)

1. The longest palindrome string (409)

Title description:

【simple】

Given a capital letter and lowercase letter string comprises, letters found by configuration longest palindromic sequence caused .

In the construction process, please pay attention to case sensitivity. For example, "Aa" cannot be used as a palindrome string.

Note: It is
assumed that the length of the string will not exceed 1010.

Example 1:

输入:
"abccccdd"

输出:
7

解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7

Topic link

Thinking analysis :

Requirement: Construct the longest palindrome string based on all the characters
of the string

\quad \quad In a palindrome, only at most one character appears odd number of times, and the remaining characters appear even number of times. Well. For a character with an even number of times, then all this character can form part of the palindrome; for a character with an odd number of times, then all this character -1 can form a part of the palindrome; finally, we add one arbitrarily An odd number of characters can form the longest palindrome string. Therefore, the idea is as follows:

  • Count characters, add even numbers directly, add odd numbers -1
  • Finally, if the character appears odd number of times, add 1 (character in the middle of the palindrome)
class Solution:
    def longestPalindrome(self, s: str) -> int:
        odd=0 #标记是否出现过奇数次数的字符,0记没有出现过
        res=0 
        counts={}#统计字符次数
        for i in s:
            counts[i]=counts.get(i,0)+1
        for key in counts.keys():
            if counts[key]%2==0:
                res+=counts[key]
            else:
                res+=counts[key]-1
                odd=max(odd,counts[key])
        return res if odd==0 else res+1
  • Time complexity: O (N) O(N)O ( N )
  • Space complexity: O (S) O (S)O ( S ) , where S is the number of different characters in the character set.

2. The longest palindrome substring (5)

Title description:

[Medium]
Give you a string s and find the longest palindrome substring in s.
Example 1:

输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。

Topic link

Solution 1: Violence Law

  • List all substrings, determine whether it is a palindrome, and save the longest palindrome.
class Solution:
    #判断字符串是否为回文字符串
    def validate_palindrome(self,s:str,left:int,right:int) -> bool:
        if len(s)<right and left<0:
            assert("s length must greater than right,left must greater than or equal to zero")
        while left < right:
            if s[left]!=s[right]:
                return False
            left+=1
            right-=1
        return True

    def longestPalindrome(self, s: str) -> str:
        n=len(s)
        if n<2:
            return s
        #用来记录回文字符串
        palindrome_s=s[0]
        #记录回文字符串长度
        max_len=1
        for i in range(n-1):
            for j in range(i+1,n):
                if j-i+1>max_len and self.validate_palindrome(s,i,j):
                    palindrome_s=s[i:j+1]
                    max_len=j-i+1
        return palindrome_s
  • Time complexity: O (n ³) O(n³)O ( n ³ ) Two-layer for loop O(n²), inside the for loop it is judged whether it is a palindrome O(n), so the time complexity is O(n³).

  • Space complexity: O(1) constant variables.

  • Can pass, but over time limit, discard

Problem solution two: dynamic programming

  • Status:
    dp[i][j] indicates whether the substring s[i…j] is a palindrome substring, where the substring s[i…j] is defined as a left-closed and right-closed interval, which can be taken as s[i] and s [j].

  • State transition equation:
    dp[i][j] = (s[i] == s[j]) and dp[i + 1][j-1]

  • Initialization: When
    initializing, a single character must be a palindrome string,
    so when the length of the string is less than 2, it must be a palindrome string, and the diagonal is initialized to true first, that is, dp[i][i] = true .

  • Output:
    As soon as you get dp[i][j] = true, record the length and starting position of the substring. There is no need to intercept it. This is because intercepting the string also consumes performance. Record the palindrome substring at this time. Start position" and "Palindrome Length".

Note: Always get the palindrome judgment of the small substring first, and then the large substring can refer to the judgment result of the small substring, that is, the order of filling in the form is very important.

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n=len(s)
        #考虑特殊情况:如果字符串的长度为1就是回文字符串
        if n<2:
            return s
        #创建一个二维列表用来保存每个字符串是否为回文字符串
        is_p= [[False] * n for _ in range(n)]
        #对角线上都是回文字符串,因为都是单个字符
        for i in range(n):
            is_p[i][i]=True
        #用来记录回文字符串的起始位置
        s_index=0
        max_len=1
        #遍历表格,计算字符串是否为回文字符串
        for j in range(1,n):
            for i in range(0,j):
                if s[i]==s[j]:
                    if j-i<3:
                        is_p[i][j]=True
                    else:
                        is_p[i][j]=is_p[i+1][j-1]
                else:
                    is_p[i][j]=False
                #记录最长的回文字符串
                current_len=j-i+1
                if is_p[i][j] and current_len>max_len:
                    max_len=current_len
                    s_index=i
        return s[s_index:(s_index+max_len)]
  • Time complexity: O (n 2) O(n^2)O ( n2)
  • Space complexity: O (n 2) O(n^2)O ( n2)

Problem solution three: center diffusion algorithm

  • Traverse each index, take this index as the center, and use the symmetry of the center of the "palindrome string" to spread to both sides to see how far it can spread.

  • When the length of the palindrome is odd and even, the form of the "palindrome center" is different.

    • The "center" of the odd palindrome string is a specific character, for example: the center of the palindrome string "aba" is the character "b";
    • The "center" of an even palindrome is the "gap" between the two characters in the middle. For example, the center of the palindrome string "abba" is the "gap" between the two "b"s.
class Solution:
    def center_spread(self,s,size,left,right):
        """中心扩散寻找回文字符串
        :param s: 字符串
        :param size: 字符串的长度
        :param left: 开始寻找左边的位置
        :param right: 开始寻找右边的位置
        :return: 回文字符串,回文字符串的长度
        """
        i=left
        j=right
        #保证在寻找的过程中不发生越界,而且左右两个字符要相等
        while i>=0 and j<size and s[i]==s[j]:
            i-=1
            j+=1
        return s[i+1:j],j-i+1
    def longestPalindrome(self, s: str) -> str:
        size=len(s)
        if size<2:
            return s
        s_palindrome=s[0]
        max_len=1
        for i in range(size):
            #当回文字符串数是奇数时
            odd_palindrome,odd_len=self.center_spread(s,size,i,i)
            #当回文字符串是偶数的时候
            even_palindrom,even_len = self.center_spread(s,size,i,i+1)
            #获取最长的回文字符串
            cur_palindrome = odd_palindrome if odd_len > even_len else even_palindrom
            #更新最长的回文字符串
            if len(cur_palindrome) > max_len:
                s_palindrome = cur_palindrome
                max_len = len(cur_palindrome)

        return s_palindrome

  • Time complexity: O (n 2) O(n^2)O ( n2)
  • Space complexity: O (1) O (1)O ( 1 )

3, Kaibunko skewer (647)

Title description:

[Medium]
Given a string, your task is to count how many palindrome substrings are in this string.

Substrings with different start positions or end positions, even if they consist of the same characters, will be regarded as different substrings.

Example 1:

输入:"abc"
输出:3
解释:三个回文子串: "a", "b", "c"

Example 2:

输入:"aaa"
输出:6
解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"

Topic link

Thinking analysis :

4. Counting binary substrings (696)

Title description:

[Simple]
Given a string s, count the number of non-empty (continuous) substrings with the same number of 0 and 1, and all 0s and all 1s in these substrings are combined.

Repeated substrings should be counted for the number of times they appear.

Example 1:

输入: "00110011"
输出: 6
解释: 有6个子串具有相同数量的连续10:“0011”,“01”,“1100”,“10”,“0011” 和 “01”。

请注意,一些重复出现的子串要计算它们出现的次数。

另外,“00110011”不是有效的子串,因为所有的0(和1)没有组合在一起。

Example 2:

输入: "10101"
输出: 4
解释: 有4个子串:“10”,“01”,“10”,“01”,它们具有相同数量的连续10

note:

  • s.length is between 1 and 50,000.
  • s contains only "0" or "1" characters.

Topic link

Thinking analysis :

Guess you like

Origin blog.csdn.net/weixin_45666566/article/details/112604535