数组中的字符串匹配
“数组中的字符串匹配”问题通常指的是:给定一个字符串数组,找出所有是其他字符串子字符串的字符串。可以用编程语言实现这一功能。
words = ["mass", "as", "hero", "superhero"]
["as", "hero"]
以下是解决该问题的代码:
def stringMatching(words):
result = []
for i, word in enumerate(words):
for j, other_word in enumerate(words):
if i != j and word in other_word:
result.append(word)
break
return result
# 示例
words = ["mass", "as", "hero", "superhero"]
print(stringMatching(words))
for 循环,检查 word 是否是 other_word 的子字符串。i == j,直接跳过。break,防止重复检查。我们可以通过先对数组按长度排序,减少不必要的比较。
def stringMatching(words):
words.sort(key=len) # 按长度排序
result = []
for i in range(len(words)):
for j in range(i + 1, len(words)): # 只检查比当前字符串长的
if words[i] in words[j]:
result.append(words[i])
break
return result
# 示例
words = ["mass", "as", "hero", "superhero"]
print(stringMatching(words))
你可以根据具体场景,选择合适的实现方法。如果有其他要求或需要进一步解释,随时告诉我!
2025 年陆剧市场依旧热度爆棚
时间:2025-09-19
阵地央一首播:年度高品质大剧,深度解锁文化抗战三重非凡意义
时间:2025-09-18
陈展鹏刘佩玥《巨塔之后》今首播
时间:2025-08-28
生万物大结局惊现最招恨角色,原来真正的坏都披着善的“羊皮”!
时间:2025-08-28
归队6集燃爆:袁姗姗化身“战地玫瑰”,实战军医双在线超吸睛!
时间:2025-08-28
许凯田曦薇新剧《子夜归》首播,点击率位列第七
时间:2025-08-21