LeetCode 336. Palindrome Pairs

Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.

Example 1:
Given words = [“bat”, “tab”, “cat”]
Return [[0, 1], [1, 0]]
The palindromes are [“battab”, “tabbat”]
Example 2:
Given words = [“abcd”, “dcba”, “lls”, “s”, “sssll”]
Return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are [“dcbaabcd”, “abcddcba”, “slls”, “llssssll”]

解:最一般的暴力超时,这里用hashtable来加速。对于词典中x,y
xright = x[:j]
xleft = x[j:]
即 x = xright | xleft
则x和y能形成回文的就2种情况:
           1、xright | xleft | y
           2、 y | xright | xleft
对1:若xright.reverse == y 且xleft == xleft.reverse,那么x+y就是回文 对2同理

hashtable将string当键值,这样查找 y的时候会快很多。

def palindromePairs(self, words):
    """
    :type words: List[str]
    :rtype: List[List[int]]
    """
hashMap = {}
for i in range(0,len(words)):
    hashMap[words[i]] = i;
List = []
size = len(words)
for i in range(0,size):
    x = words[i]
    for j in range(0,len(x)+ 1):
        xpre = x[:j]
        resxpre = x[j:]
        match1 = hashMap.get(xpre[::-1])
        if (match1 != None) & (resxpre == resxpre[::-1]) & (match1 != i):
            List.append([i,match1])
        match2 = hashMap.get(resxpre[::-1])
        #这里j != 0 为了防止重复,在上面加j!=len(x)也行
        if (match2 != None) & (xpre == xpre[::-1])& (match2 != i) & (j != 0):
            List.append([match2,i])
return List

上面有一个问题就是当x + y和y+x 都为全字符串的时候,会重复,设定规则,在全字符串时,仅加xright | xleft | y这种情况 。

你可能感兴趣的:(acm,leetcode)