LeetCode30 Hard 查找所有子串

本文介绍了LeetCode30题的难点和暴力解法,然后通过两步优化(Two pointers)降低时间复杂度,从暴力的O(n^2)优化到更高效的解决方案,适合于字符串和算法学习者参考。
摘要由CSDN通过智能技术生成

本文始发于个人公众号:TechFlow,原创不易,求个关注


链接

Substring with Concatenation of All Words


难度

Hard


描述


给定一个字符串s作为母串,和一系列长度相等的字符串words,要求返回s当中所有的位置,使得从该位置开始可以找到所有的words,并且所有的words只出现一次

You are given a string, s , and a list of words, words , that are all
of the same length. Find all starting indices of substring(s) in s that is
a concatenation of each word in words exactly once and without any
intervening characters.


样例 1:

**Input:
  s =**  "barfoothefoobarman",
**words =** ["foo","bar"]
Output: [0,9]
## Explanation: Substrings starting at index 0 and 9 are  "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.

样例 2:

**Input:
  s =**  "wordgoodgoodgoodbestword",
**words =** ["word","good","best","word"]
Output: []

题解


这道题的难度是Hard,老实讲的确不简单,尤其是如果在面试当中被问到,恐怕很难一下想出最佳答案。


暴力


还是老规矩,我们退而求其次,忘了最佳答案这茬,先想出简单的方法再来思考怎么优化。最简单的方法当然是暴力,我们首先遍历所有的起始位置,然后后面一个单词一个单词的匹配。如果成功匹配就记录答案,失败的话则继续搜索下一个位置。

这么做看起来没有问题,但是一些细节需要注意。比如题目当中只说单词的长度一样,并没有说单词会不会重复。显然我们应该考虑单词出现重复的情况,既然要考虑单词出现重复,那么就不能用一个set来记录单词是否出现过,而是需要统计每个单词出现的个数。其次,我们在遍历的时候,也一样,也需要统计当前匹配到的单词的数量。

这道题暴力的思路还是比较清晰的,代码也不难写:

class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:
        n = len(s)
        # 单词不存在直接返回
        if len(words) == 0:
            return []
        
        ret = []
        word_cnt = len(words)
        m = len(words[0])
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值