Substring with Concatenation of All Words
s: "barfoothefoobarman"
words: ["foo", "bar"]
You should return the indices: [0,9].
这一题想了很久,基础太烂,只能参考了讨论区的答案
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> findSubstring(string s, vector<string> &words) {
vector<int> indices;
unordered_map<string, int> count;
for (string word:words)
count[word]++;
int num = words.size();
int len = words[0].length();
int n = s.length();
for (int i = 0; i < n - len * num+1; i++) {
unordered_map<string, int> seen;
int j = 0;
for (; j < num; j++) {
string word = s.substr(i + j * len, len);
if (count.find(word) != count.end()) {
seen[word]++;
if (seen[word] > count[word]) {
break;
}
} else
break;
}
if (j == num)
indices.push_back(i);
}
return indices;
};
};
具体思路:
在一个字符串中寻找一个vector<string>,每一次只需要找vector长度。
理清楚判断寻找成功,和失败的条件。
成功:在指定长度内找到指定个word,一个word不能多(如果少了,有两种失败情况:1.其他word多了2.word匹配错误)
网友评论