Substring with Concatenation of All Words
原题链接Substring with Concatenation of All Words
题目意思是给定字符串s和字符数组words,在s中寻找words出现的位置,words内部的字符串顺序没有要求
此问题可以直接顺序搜索,假设s
的长度为m,words
的长度为n,words
中每个单词的长度为w,复杂度是O((m-n*w)*n)
,需要利用两个unordered_map<string,int>
,一个记录每个单词总共需要多少个,一个记录当前遍历到的单词数,如果遇到不在words
中的单词,就break
从下一个开始找
另一种方法是使用滑动窗口,也是利用两个unordered_map<string, int>
。原理是当不匹配是移动起始点,每一移动w个距离。不匹配有两种情况
- 当前单词不是words中的单词,重新开始找,初始化负责记录遍历到的单词数的那个map
- 当前单词word是words中的单词,但是这个单词已经够了,不再需要这个单词了。此时需要将窗口向右移动,直到出现第一个word为止,从这个word后面开始记录
举个例子,
s = "barfoobarfoothebar";
words = ["bar","bar","foo","the"];