1408. 数组中的字符串匹配 - 力扣(LeetCode)
可以使用 Python 来解决这个问题。思路如下:
-
遍历所有单词,检查它是否是 其他单词的子字符串。
-
双层遍历:对于每个单词,遍历数组中的所有其他单词,检查它是否是对方的子串。
-
使用 set() 去重,防止重复的结果。
代码实现:
def string_matching(words):
result = set()
for i in range(len(words)):
for j in range(len(words)):
if i != j and words[i] in words[j]: # words[i] 是 words[j] 的子串
result.add(words[i])
return list(result)
# 测试示例
words = ["mass", "as", "hero", "superhero"]
print(string_matching(words)) # 输出: ["as"]
复杂度分析:
-
时间复杂度: O(n2⋅m),其中 n 是单词数,m 是单词的最大长度。
-
空间复杂度: O(n),用于存储结果集。
这样,你就可以得到所有作为 其他单词子串 的单词啦! 🚀