1408.数组中的字符串匹配

一、题目:

给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 words
中是其他单词的子字符串的所有单词。

如果你可以删除 words[j] 最左侧和/或最右侧的若干字符得到 word[i] ,那么字符串 words[i] 就是 words[j]
的一个子字符串。

示例 1:

输入:words = [“mass”,“as”,“hero”,“superhero”]
输出:[“as”,“hero”]
解释:“as” 是"mass" 的子字符串,“hero” 是 “superhero” 的子字符串。
[“hero”,“as”] 也是有效的答案。

示例 2:

输入:words = [“leetcode”,“et”,“code”]
输出:[“et”,“code”]
解释:“et” 和 "code"都是 “leetcode” 的子字符串。

示例 3:

输入:words = [“blue”,“green”,“bu”]
输出:[]

二、解题

方法一:暴力破解

思路:
1、双层循环
2、取列表中的任意两个字符串,定义一个方法match()专门用来比较:其中一个字符串是否是另一个字符串的子串,其中,方法有:暴力算法和kmp算法,这里使用了暴力算法。
3、将match()中的结果True或者False返回

代码如下

def match(str1,str2): #  as mass
    i,j = 0,0
    while i < len(str2) and j < len(str1):
        if str2[i] == str1[j]:
            i += 1
            j += 1
        else:
            i = i - j + 1
            j = 0
    if j >= len(str1):
        return True
    else:
        return False

def stringMatching(words):
    res = []

    for i in range(len(words)):
        j = 0
        while j < len(words):
            if i == j:
                j += 1
            if j<len(words) and len(words[i]) <= len(words[j]):
                if match(words[i],words[j]) == True:
                    res.append(words[i])
            j += 1
    #去重
    res = list(set(res))
    return res

if __name__ == '__main__':
    words = ["leetcoder","leetcode","od","hamlet","am"]
    print(stringMatching(words))
    # print(words)

结果:
在这里插入图片描述

三、知识点

set()方法可以给list列表去重

res = list(set(res))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值