美文网首页
336. Palindrome Pairs

336. Palindrome Pairs

作者: April63 | 来源:发表于2018-06-15 14:35 被阅读0次

这一题 想到的就是一个o(n2)的方法,会超时,discussion里面有个写法很6,我重新写会有些case过不去,先放它的原本的代码,如下:

class Solution(object):
    def palindromePairs(self, words):
        """
        :type words: List[str]
        :rtype: List[List[int]]
        """
        def is_palindrome(check):
            return check == check[::-1]

        words = {word: i for i, word in enumerate(words)}
        valid_pals = []
        for word, k in words.iteritems():
            n = len(word)
            for j in range(n+1):
                pref = word[:j]
                suf = word[j:]
                if is_palindrome(pref):
                    back = suf[::-1]
                    if back != word and back in words:
                        valid_pals.append([words[back],  k])
                if j != n and is_palindrome(suf):
                    back = pref[::-1]
                    if back != word and back in words:
                        valid_pals.append([k, words[back]])
        return valid_pals

相关文章

  • 2019-04-07

    LeetCode 336. Palindrome Pairs Description Given a list o...

  • 336. Palindrome Pairs

    Leetcode: 336.Palindrome PairsGiven a list of unique word...

  • 336. Palindrome Pairs

    这一题 想到的就是一个o(n2)的方法,会超时,discussion里面有个写法很6,我重新写会有些case过不去...

  • LeetCode 336. Palindrome Pairs

    对每个word,如果它翻转过来之后[:n]或者[n:]和map中已有的key相同,且剩下的一部分是palindro...

  • [leetcode] 336. Palindrome Pairs

    Given a list of unique words, find all pairs of distinct ...

  • Leetcode 336. Palindrome Pairs

    文章作者:Tyan博客:noahsnail.com[http://noahsnail.com] | CSDN[ht...

  • 8.19 - hard - 70

    336. Palindrome Pairs 基本想出来是怎么做,只是一上来就想去优化,结果想的有点乱,其实最好的方...

  • Palindrome Pairs

    Given a list of unique words, find all pairs of distinct ...

  • Palindrome Pairs

    题目Given a list of unique words, find all pairs of distinc...

  • Palindrome Pairs

    题目来源给一个字符串数组,求能组成回文串的两个元素的。就是比较烦,但是倒不是很难。代码如下:

网友评论

      本文标题:336. Palindrome Pairs

      本文链接:https://www.haomeiwen.com/subject/kqhmeftx.html