Substring with concatenation of all Words
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 that's a concatenation of each word in words exactly once and without any Intervening characters.
For example, given:s: "Barfoothefoobarman" words:["foo", "Bar"]
You should return to the indices: [0,9] (order does not matter).
Test Instructions
Given a string of s and a string array, the length of the string in l,l is equal, find all the substrings in S, the substring contains all the characters in L once and does not contain any other characters, returning all the starting positions of this string.
Analysis
The string array L is built with a map character window that matches the character window from the first character of the string s and slides backwards until the last character of S, outputting the matching result.
C++11 Code
//Time complexity O (n*m), Space complexity O (m)classSolution { Public: vector<int>Findsubstring (stringS vector<string>& dict) {size_t wordlength = Dict.front (). Length (); size_t catlength = wordlength * Dict.size (); vector<int>Resultif(S.length () < catlength)returnResult unordered_map<string, int>WordCount; for(Auto Const& Word:dict) {++wordcount[word]; } for(Autoi = begin (s); I <= prev (end (s), catlength); ++i) { unordered_map<string, int>Unused (WordCount); for(Autoj = i; J! = Next (i, catlength); J + = Wordlength) {Autopos = Unused.find (string(J, Next (J, Wordlength)));if(pos = = Unused.end () | | pos->second = =0) Break;if(--pos->second = =0) Unused.erase (POS); }if(unused.size () = =0) Result.push_back (distance (begin (s), i)); }returnResult }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode:substring with concatenation of all Words