码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode-184周赛-5380-数组中的字符串匹配

时间:2020-04-12 20:41:27      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:题目   range   image   leetcode   color   etc   app   bre   style   

 题目描述:

技术图片

 

 技术图片

 

 自己的提交:

class Solution:
    def stringMatching(self, words: List[str]) -> List[str]:

        def strStr(haystack: str, needle: str) -> int:
            if not needle:return 0
            def getNext(s):
                next_ = [0] * len(s)
                next_[0] = -1
                i = 0
                j = -1
                while i < len(s) - 1:
                    if j == -1 or s[i] == s[j]:
                        j += 1
                        i += 1
                        if s[i] == s[j]:
                            next_[i] = next_[j]
                        else:
                            next_[i] = j
                    else:
                        j = next_[j]
                return next_
            next_ = getNext(needle)
            i,j = 0,0
            while i < len(haystack) and j < len(needle):
                if j == -1 or haystack[i] == needle[j]:
                    i += 1
                    j += 1
                else:
                    j = next_[j]
            if j == len(needle):
                return i - j
            return -1

        words.sort(key=lambda x: len(x))
        # print(words)
        ans = set()
        for i in range(len(words)):
            for j in range(i+1, len(words)):
                if strStr(words[j], words[i]) >= 0:
                    ans.add(words[i])
        return list(ans)

另:

class Solution:
    def stringMatching(self, words: List[str]) -> List[str]:
        ans = []
        for word in words:
            for word2 in words:
                if word != word2 and word in word2:
                    ans.append(word)
                    break
        return ans

 

leetcode-184周赛-5380-数组中的字符串匹配

标签:题目   range   image   leetcode   color   etc   app   bre   style   

原文地址:https://www.cnblogs.com/oldby/p/12687071.html

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