美文网首页
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
    

    相关文章

      网友评论

          本文标题:336. Palindrome Pairs

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