Substring with concatenation of all Words (HashTable)

Source: Internet
Author: User

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)

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• Sales Support

1 on 1 presale consultation

• After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.