题目:
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).
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
if (L.size() == 0 || S.size() < L[0].size()* L.size())
return vector<int>(0);
vector<int> res;
unordered_map<string, int> table;
unordered_map<string, int> cur;
//建立单词表
for (int i = 0; i < L.size(); i++) {
if (table.find(L[i]) == table.end())
table[L[i]] = 1;
else
table[L[i]]++;
}
//每个单词长度
int wl = L[0].size();
//单词个数
int wn = L.size();
for (int i = 0; i <= S.size() - wn*wl; i++) {
cur.clear();
int j;
for (j = 0; j < wn; j++) {
string s = S.substr(i + j* wl, wl);
//单词不在表中
if (table.find(s) == table.end())
break;
cur[s]++;
if (cur[s] > table[s])
break;
}
if (j == wn)
res.push_back(i);
}
return res;
}
};