題目:
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is 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 the indices: [0,9].
(order does not matter).
鏈接:Substring with Concatenation of All Words
解法:枚舉子串,切分後用map判斷。時間O(n*m)
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
map<string, int> mwords;
map<string, int> curWords;
vector<int> ret;
int slen = s.length();
if (!slen || words.empty()) return ret;
int llen = words.size(), wlen = words[0].length();
for (vector<string>::iterator i = words.begin(); i != words.end(); i++) mwords[*i]++;
for (int i = 0; i + llen * wlen <= slen; i++) {
curWords.clear();
int j = 0;
for (j = 0; j < llen; j++) {
string tmp = s.substr(i + j * wlen, wlen);
if (mwords.find(tmp) == mwords.end())
break;
++curWords[tmp];
if (curWords[tmp] > mwords[tmp])
break;
}
if (j == llen) ret.push_back(i);
}
return ret;
};
};
Runtime: 152 ms