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 shoshould return the indices:[0,9].
(Order does not matter ).
Analysis: brute-force, first use an unordered_map word_count to record the number of occurrences of words in L, and then use a loop from the first character of S to the end of S. size () * l [0]. the length () character that matches the word in L. In each of the above loops, a temporary unordered_map unused is used to record the number of remaining occurrences of the current word (the number of occurrences of the word in word_count minus the number of occurrences of the word ), if the current word does not appear in word_count or the remaining number of occurrences of the word is 0, it indicates that the S substring currently searched is not a combination of the words in L; otherwise, subtract one of the remaining occurrences of the word and determine whether the remaining occurrences are 0. If the remaining occurrences are 0, remove the word from unused. Finally, determine whether unused is null. If it is null, it indicates that a combination of all words in L has been found, and the index in the outermost loop is placed in the result.
class Solution {public: vector<int> findSubstring(string S, vector<string> &L) { vector<int> res; int l = L.size(); if(l == 0) return res; int wl = L[0].length(); if(S.length() < l*wl) return res; unordered_map<string, int> word_count; for(auto w:L) word_count[w]++; for(int i = 0; i <= S.length()-l*wl; i++){ unordered_map<string,int> unused(word_count); for(int j = i; j < i+l*wl ; j += wl){ auto pos = unused.find(S.substr(j,wl)); if(pos == unused.end() || pos->second == 0) break; if(--(pos->second) == 0) unused.erase(pos); } if(unused.empty()) res.push_back(i); } return res; }};
Substring with concatenation of all words