1408. 数组中的字符串匹配
题目:给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 words 中是其他单词的子字符串的所有单词。
链接 https://leetcode.cn/problems/string-matching-in-an-array/
个人思路
- 注意到words[i]与words[j]之间可能是对方的子字符串,所以得使用两次循环,且是类似与放回抽取,但还是忽略了一种情况,那就是words[i]是words[j]的子字符串,同时也是words[k]的子字符串,所以得判断是否已经添加进数组,或者添加进数组以后就break掉第二个循环
class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
ans = []
for word1 in words:
for word2 in words:
if word1 != word2 and word1 in word2:
ans.append(word1)
break
return ans
时间复杂度:O(n2 × L2),其中 n 是字符串数组的长度,L 是字符串数组中最长字符串的长度。使用KMP 字符串匹配算法可以将时间复杂度优化到O(n2 × T),其中 T 是字符串数组中所有字符串的平均长度。
空间复杂度:O(1)。返回值不计入空间复杂度。如果使用 KMP 字符串匹配算法,那么对应的空间复杂度为 O(T)。
- 题解下面的评论:AC自动机可以达到线性复杂度
可以看看:
https://leetcode.cn/problems/string-matching-in-an-array/solution/shu-zu-zhong-de-zi-fu-chuan-pi-pei-by-le-rpmt/