You is given a string, s, and a list of words, words, that is all of the same length. Find all starting indices of substring (s) in S, a concatenation of each word in wordsexactly once and without any I ntervening characters.
For example, given:
S"barfoothefoobarman"
Words["foo", "bar"]
You should return the indices: [0,9]
.
(Order does not matter).
Idea: To determine whether a value is contained in an array, you should first think of putting the elements in this array into Hashtable, otherwise the time complexity of O (n) is required for each lookup.
Time complexity: O (n*size), where n is the length of s, and size is the number of elements that the exponential group words contains. When the words element is not many, we can say that the time complexity is linear O (n)
classSolution { Public: Vector<int> findsubstring (stringS, vector<string>&words) {Size=words.size (); Slen=s.length (); Wlen= words[0].length (); Wordslen= Wlen *size; for(i =0; i < size; i++) {Word_counter[words[i]]++; } I=0; while(i+wordslen<=Slen) { for(j =0; J < size; J + +) {Cmpstr= S.substr (i+j*Wlen, Wlen); if(Word_counter.find (cmpstr) = =Word_counter.end ()) { Break; } Counting[cmpstr]++; if(counting[cmpstr]>Word_counter[cmpstr]) { Break; } } if(j==size) {Ret.push_back (i); } counting.clear (); I++; } returnret; }Private: stringCmpstr; Vector<int>ret; Map<string,int>Word_counter; Map<string,int>counting; intSize//Number of words intSlen; intWlen; intWordslen; inti; intJ;};
Substring with concatenation of all Words (HashTable)