四个词各出现几次
四个要找的词 he、she、his、hers,一段文本 ushershishe(11 个字符,下标从 0 起)。
按 WORDS 里的顺序,输出四个词各自的出现次数:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#include <algorithm>
#include <map>
#include <utility>
const vector<string> WORDS = {"he", "she", "his", "hers"};
const string TXT = "ushershishe";
struct TNode {
map<char, TNode*> next;
string word; // 不空:有一个词在这里结束
};
TNode* build(const vector<string>& words) {
TNode* root = new TNode();
for (const string& w : words) {
TNode* node = root;
for (char ch : w) {
if (!node->next.count(ch)) node->next[ch] = new TNode();
node = node->next[ch];
}
node->word = w;
}
return root;
}
vector<pair<int, string>> scan(TNode* root, const string& txt) {
vector<pair<int, string>> hits;
for (int i = 0; i < (int)txt.size(); i++) {
TNode* node = root;
for (int j = i; j < (int)txt.size(); j++) {
auto it = node->next.find(txt[j]);
if (it == node->next.end()) break;
node = it->second;
if (!node->word.empty()) hits.push_back({i, node->word});
}
}
sort(hits.begin(), hits.end());
return hits;
}
int main() {
auto hits = scan(build(WORDS), TXT);
for (size_t k = 0; k < WORDS.size(); k++) {
int c = 0;
for (auto& h : hits) if (h.second == WORDS[k]) c++;
cout << (k ? "/" : "") << c;
}
cout << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论