[Leetcode] Substring with Concatenation of All Words
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]
.
老是超时,终于过了。
1 class Solution { 2 public: 3 vector<int> findSubstring(string S, vector<string> &L) { 4 vector<int> res; 5 if (L.size() < 1) return res; 6 7 int Len = L.size() * L[0].length(); 8 int len = L[0].length(); 9 if (S.length() < Len) return res; 10 11 map<string, int> word_count; 12 for (int i = 0; i < L.size(); ++i) { 13 word_count[L[i]]++; 14 } 15 map<string, int> word_detect; 16 for (int i = 0; i <= S.length() - Len; ++i) { 17 word_detect.clear(); 18 string substr; 19 int j = 0; 20 for (j = 0; j < Len; j += len) { 21 substr = S.substr(i + j, len); 22 if (word_count.find(substr) == word_count.end()) 23 break; 24 ++word_detect[substr]; 25 if (word_detect[substr] > word_count[substr]) 26 break; 27 } 28 if (j==Len) res.push_back(i); 29 } 30 return res; 31 } 32 };