标签:
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]
.
(order does not matter).
[Solution]
1 vector<int> findSubstring(string S, vector<string> &L) 2 { 3 map<string, int> wcount; 4 vector<int> result; 5 int i = 0, j = 0; 6 if (L.size() == 0) 7 return result; 8 9 int len = L[0].size(), lsize = L.size(); 10 for (i = 0; i < L.size(); i++) 11 wcount[L[i]]++; 12 13 for (i = 0; i <= (int)(S.size() - len * lsize); i++) 14 { 15 map<string, int> table; 16 for (j = 0; j < lsize; j++) 17 { 18 string word = S.substr(i + j * len, len); 19 if (wcount.find(word) == wcount.end()) 20 break; 21 table[word]++; 22 if (table[word] > wcount[word]) 23 break; 24 } 25 if (j == lsize) 26 result.push_back(i); 27 } 28 29 return result; 30 }
[*leetcode 30] Substring with Concatenation of All Words
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4420934.html