码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] 336. Palindrome Pairs_Hard

时间:2018-06-21 11:34:26      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:pairs   style   AC   href   leetcode   tin   hat   ati   index   

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"]

 

这道题的思路就是把每个word和index存到diction里面, 然后针对每个word, for loop, 拆分为两部分, 如果前面部分是palindrome, 那么把后面部分的单词reverse, 如果reverse后的单词在diction里面, ans.append(d[back], index); 同理, 如果后面部分是palindrome, 把前面部分的单词reverse, 如果reverse后的单词在diction里面, ans.append(index, d[back]). 此时需要注意的是在后面check的时候就不要考虑整个单词reverse的情况, 因为前面单词reverse的时候已经考虑到了. 如果不明白的话就用set去去重, 最保险的做法.

参考Solution.

 

class Solution(object):
    def palindromePairs(self, words):
        """
        :type words: List[str]
        :rtype: List[List[int]]
        """
        def checkpal(w):
            return w == w[::-1]  # 反正O(n), 所以用最粗暴的方式

        d, ans = {w:index for index, w in enumerate(words)},[]
        for word, index in d.items():
            l = len(word)
            for i in range(l+1): # l+1 因为pref要到[:l]
                pref = word[:i]
                suf = word[i:]
                if checkpal(pref):
                    back = suf[::-1]
                    if back != word and back in d:
                        ans.append([d[back], index])
    
                if i != l and checkpal(suf): # delete the duplicates
                    back = pref[::-1]
                    if back != word and back in d:
                        ans.append([index, d[back]])
        return ans

 

[Leetcode] 336. Palindrome Pairs_Hard

标签:pairs   style   AC   href   leetcode   tin   hat   ati   index   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/9206896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!