题目
给一个字符串s 和一些长度相同的单词words, 在s 里找到所有words按任意顺序组成的子字符串,并返回这些子字符串的起始位置
例如: s = “barfooothefoobarman” words = [“foo”, “bar”]
返回 [0, 10]
结论:
s: “barfooothefoobarman”
words: [“foo”, “bar”]
res: [0, 10]
s: “wordgoodgoodgoodbestword”
words: [“word”, “good”, “best”, “word”]
res: []
s: “barfoofoobarthefoobarman”
words: [“bar”, “foo”, “the”]
res: [6, 9, 12]
代码
思考: S一个一个字符步进,并遍历所有words,找出匹配的字符,匹配的话标记该word被匹配,然后从S找下一个匹配的word, 直到words都匹配完了,就以得一个开始位置 。S字符步进,不管有没有匹配到word都是按1步进
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <time.h>
#include <assert.h>
#include <random>
std::vector<std::size_t> try_find_word(const std::string& str, const std::vector<std::string>& words) {
std::size_t index = 0;
std::vector<bool> is_checked(words.size());
std::size_t total_word_count = 0;
for (auto it : words) {
total_word_count += it.size();
}
std::vector<std::size_t> res;
while (index < str.size()) {
std::fill(is_checked.begin(), is_checked.end(), false);
std::size_t cur_index = index;
std::size_t find_count = 0;
std::size_t i = 0;
while (i < words.size()&&cur_index < str.size()) {
bool is_find = false;
if (!is_checked[i]) {
if (str.at(cur_index) == words[i].at(0)) {
if (str.compare(cur_index, words[i].size(), words[i]) == 0) {
is_checked[i] = true;
is_find = true;
++find_count;
cur_index += words[i].size();
}
}
}
i = is_find ? 0 : i + 1;
}
if (find_count == words.size()) {
res.push_back(index);
++index;
}else {
++index;
}
}
return res;
}
namespace std {
std::ostream& operator<<(std::ostream& os, const std::vector<std::string>& v) {
os << "[";
if (!v.empty()) {
auto it = v.begin();
os << "\"" << *it << "\"";
it++;
for (; it != v.end(); ++it) {
os << ", \"" << *it << "\"";
}
}
os << "]";
return os;
}
std::ostream& operator<<(std::ostream& os, const std::vector<std::size_t>& v) {
os << "[";
if (!v.empty()) {
auto it = v.begin();
os << *it;
it++;
for (; it != v.end(); ++it) {
os << ", " << *it;
}
}
os << "]";
return os;
}
}
void output_res(const std::string& str, const std::vector<std::string>& words) {
std::vector<std::size_t> res = try_find_word(str, words);
std::cout << "s: \"" << str << "\"" << std::endl << "words: "<< words << std::endl << "res: " << res << std::endl;
}
void test_find_word() {
output_res("barfooothefoobarman", { "foo", "bar" });
output_res("wordgoodgoodgoodbestword", { "word", "good", "best", "word" });
output_res("barfoofoobarthefoobarman", { "bar", "foo", "the" });
}