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).
这题,我没有什么好的做法。
采取的是最笨的方法:枚举。
具体做法:
在S串中枚举一个可能的Substring开始的位置然后进行验证。
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> ans;
if (L.size() == 0) {
return ans;
}
int eL = L[0].size(), n = L.size();
if (eL * n > S.size()) {
return ans;
}
map<string, int> lists;
for (vector<string>::iterator iter = L.begin(); iter != L.end(); iter++) {
lists[*iter]++;
}
map<string, int> temp;
string sub;
for (int i = 0; i <= S.size() - n * eL; i++) {
temp.clear();
temp.insert(lists.begin(), lists.end());
int j = i, count = temp.size();
while (true) {
sub = S.substr(j, eL);
int q = --temp[sub];
if (q < 0) {
break;
}
if (q == 0) {
count--;
if (count == 0) {
ans.push_back(i);
break;
}
}
j += eL;
}
}
return ans;
}
};