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

 题目描述:

 

 自己的提交:

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

猜你喜欢

转载自www.cnblogs.com/oldby/p/12687071.html
今日推荐