Leetcode 336. Palindrome vs. Python

Time:2020-11-22

336. Palindrome is right


Source: leetcode https://leetcode-cn.com/problems/palindrome-pairs

subject


Given a unique set of words, find all the different index pairs(i, j), so that the two words in the list,words[i] + words[j]Can be spliced into palindrome strings.

Example 1:

Input: ["ABCD", "DCBA", "LLS", "s", "sssll"]
Output: [[0,1], [1,0], [3,2], [2,4]]
Explanation: the palindrome strings that can be spliced are ["dcbaabcd", "abcddcba", "SLLS", "llssssll"]

Example 2:

Input: [bat "," tab "," cat "]
[0], [1,0]
Explanation: palindrome strings that can be spliced are ["battab", "tabbat"]

Thinking of problem solving


Idea: enumeration, hash table

First of all, look at the title. The title indicates that the words in the given list are unique, and judge whether there are words with different indexes that can form palindrome strings?

In the example, we found that the lengths of the strings that make up palindrome strings are not necessarily equal. Suppose that when there are two string words a and B, a + B is a palindrome string, and the length of the two strings is a respectively_ len、b_ len。 According to the example, we will analyze the situation

  1. Whena_len = b_lenThen a must be the flip of B;
  2. Whena_len > b_lenSince the length of B is small, a palindrome string must be formed at this time. There must be some palindrome strings in a. Then a is divided into two parts: A1 and A2. The first part is the reversal of B, while A2 itself is palindrome string;
  3. Whena_len < b_lenIn fact, this situation is the opposite of the above one. B is also divided into two parts: B1 and B2. B1 itself is palindrome string, while B2 is the flip of A.

From the above analysis, we can find that all the disassembled strings are long strings. So, now that we can try to enumerate each string I as a longer string, we can now split it into I1 and I2. Then there will be two situations:

  • When I1 is a palindrome string, the third case above is met here, as long as we find out whether there is I2 flip in the sequence of subsequent strings.
  • When I2 is a palindrome string, the second case above is met, as long as we find out whether there is I1 flip in the subsequent string sequence.

Here, you need to pay attention to one case, that is, the empty string. Because an empty string is also a palindrome string. In the above disassembly process, when the string I is disassembled and one of I1 and I2 is an empty string, this situation is in line with the first case analyzed above.

Now the main thing is how to determine whether the flipped substring of the split substring exists in the given string list?

Here, consider using a hash table to store flipped strings for all strings. Then, when querying the split substring, we can get the result as long as we judge whether it is in the hash table.

The specific code implementation is as follows.

code implementation


from typing import List

class Solution:
    def palindromePairs(self, words: List[str]) -> List[List[int]]:
        
        def is_palindrome(str, start, end):
            Check whether the substring is palindrome string
            """
            part_word = str[start:end+1]
            return part_word == part_word[::-1]

        def find_reversed_word(str, start, end):
            Find whether the substring is in the hash table
            Return:
                Not in hash table, return - 1
                Otherwise, the corresponding index is returned
            """
            part_word = str[start:end+1]
            ret = hash_map.get(part_word, -1)
            return ret
        
        #Builds a hash table to store flipped strings of strings in a given list
        #The key is the flipped string, and the value is the index corresponding to the string before flipping
        hash_map = {}
        for i in range(len(words)):
            word = words[i][::-1]
            hash_map[word] = i
        
        res = []
        
        #Traverse the string, split the string, and judge
        for i in range(len(words)):
            word = words[i]
            word_len = len(word)
            #First judge the existence of an empty string. If the current string is a palindrome string (not an empty string), it is combined with the current string and put into the result
            if is_palindrome(word, 0, word_len-1) and "" in hash_map and word != "":
                res.append([hash_map.get(""), i])
            for j in range(word_len):
                #First, check whether the right part is palindrome string after division
                if is_palindrome(word, j, word_len - 1):
                    #Find whether the flip of the left part of the substring is in the hash table
                    left_part_index = find_reversed_word(word, 0, j-1)
                    #When the index value returned is not - 1 and is not the index corresponding to the current string,
                    #Indicates that there are two strings that can form palindrome strings and add the index to the result list
                    if left_part_index != -1 and left_part_index != i:
                        res.append([i, left_part_index])
                #The principle is the same as above, but at this time, we can judge whether the left part is palindrome string
                if is_palindrome(word, 0, j-1):
                    #Determine whether the right part of the substring flip is in the hash table
                    right_part_index = find_reversed_word(word, j, word_len-1)
                    if right_part_index != -1 and right_part_index != i:
                        res.append([right_part_index, i])

        return res


words = ["a", ""]
solution = Solution()
solution.palindromePairs(words)

Achieving results


Leetcode 336. Palindrome vs. Python

Welcome to our attention


The official account [book collection]