题目:
You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
分析与解答:乍一看好像挺难的,其实难度并不大。一般碰到无法直接求解的题目,不妨先把题目简化一下,看看能不能转换为比较好解的问题。比如这个题,如果L中是一个一个字符而不是单词的话,那就简单多了。还是要维护一个S上的滑动窗口,和之前的Longest Substring Without Repeating Characters解法差不多。用hash来判断某个S中的某个字符是不是在L中,如果在就将窗口右移动。如果不在就将窗口清零,从下个字符开始重新搜索。需要注意的是,L中可能有重复的字符,所以会出现这种情况,当我在S中扫描到一个字符,比如a时,可能它在窗口中出现的次数超过了L中出现的次数,那么此时不能将窗口清零,而是左端向右保持移动直到第一次碰到a,将左端移动到a的右边即可。复杂度,由于循环中是按wordLen而不是字符来前进的,而S中每个字符都只能作为一个单词的开头,而且每个单词最多考察2次,所以复杂度应为O(n),n为S的长度。
找到简化问题的解,那么原问题也容易多了,只需要将循环的开头设置为S[0],S[1]....S[wordLen-1],每次都重复上面的过程即可。
class Solution { public: vector<int> findSubstring(string S, vector<string> &L) { vector<int> result; if(S == "" || L.size() == 0) return result; int wordLen = L[0].size(),SLen= S.size(),LLen = L.size(); unordered_map<string,int> words;//存放所有L中的单词以及其出现次数 words.clear(); for(int i = 0; i < LLen; i++) { words[L[i]]++; } unordered_map<string,int> cur;//存放结果,看是否与words相等。 for(int i = 0; i < wordLen; i++) { cur.clear(); int left = i;//left指向滑动窗包含的第一个字符,right指向滑动窗的后一个字符。 int count = 0;//记录cur中单词的个数 for(int right = left ; SLen - left >= LLen*wordLen; right += wordLen) { string word = S.substr(right,wordLen);//获取下一个单词 if(words.find(word) != words.end()) //如果在L中 { cur[word]++; count++; if(cur[word] > words[word]) //加入cur后,如果这个词的出现次数超过L中该词的出现次数,将left左移至word第一次出现的右边。 { while(S.substr(left,wordLen) != word) { cur[S.substr(left,wordLen)]--; left += wordLen; count--; } left += wordLen; count--; cur[word]--; } } else //不在L中,查找失败,将窗口重置,从下一个单词开始重新检查。 { cur.clear(); left = right + wordLen; count = 0; } if(count == LLen) //如果找到一个结果,滑动窗左移一个单词,继续寻找。 { cur[S.substr(left,wordLen)]--; count --; result.push_back(left); left +=wordLen; } } } return result; } };