static int x=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
if (s.length() <= 0 || words.size() <= 0)
return res;
unordered_map<string, int> list;
unordered_map<string, int> temp;
for (string word : words)
list[word]++;
int word_len = words[0].length();
int word_num = words.size();
int words_len = word_num * word_len;
int len = s.length();
int i, j;
for (i = 0; i < word_len; i++) {
int left = i;
int cnt = 0;
for (j = i; j <= len - word_len; j += word_len) {
string str = s.substr(j, word_len);
if (list.count(str) == 1) {
temp[str]++;
if (temp[str] <= list[str])
cnt++;
else {
// 清除前面的单词
while (temp[str] > list[str]) {
string t = s.substr(left, word_len);
temp[t]--;
if (temp[t] < list[t])
cnt--;
left += word_len;
}
}
// 滑动窗口
if (cnt == word_num) {
res.push_back(left);
temp[s.substr(left, word_len)]--;
cnt--;
left += word_len;
}
}
else {
temp.clear();
cnt = 0;
left = j + word_len;
}
}
temp.clear();
}
return res;
}
};
LetCode 30. 与所有单词相关联的字串
最新推荐文章于 2019-04-21 14:00:03 发布