本文始发于个人公众号: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])
words

本文介绍了LeetCode30题的难点和暴力解法,然后通过两步优化(Two pointers)降低时间复杂度,从暴力的O(n^2)优化到更高效的解决方案,适合于字符串和算法学习者参考。
最低0.47元/天 解锁文章
1492

被折叠的 条评论
为什么被折叠?



