class Trie {
public:
struct Node {
Node * son[26];
bool is_end;
Node() {
for(int i = 0; i < 26; i ++ ) son[i] = nullptr;
is_end = false;
}
}*root;
/** Initialize your data structure here. */
Trie() {
root = new Node();
}
/** Inserts a word into the trie. */
void insert(string word) {
auto p = root;
for(auto c : word) {
int u = c - ‘a‘;
if(!p->son[u]) p->son[u] = new Node();
p = p->son[u];
}
p->is_end = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
auto p = root;
for(auto c : word) {
int u = c - ‘a‘;
if(!p->son[u]) return false;
p = p->son[u];
}
return p->is_end;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
auto p = root;
for(auto c : prefix) {
int u = c - ‘a‘;
if(!p->son[u]) return false;
p = p->son[u];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e6 + 10;
int n, m;
char str[N];
int son[N][26], cnt[N], idx;
void insert(char *str) // 插入字符串
{
int p = 0;
for (int i = 0; str[i]; i ++ )
{
int u = str[i] - ‘a‘;
if (!son[p][u]) son[p][u] = ++ idx;
p = son[p][u];
}
cnt[p] ++ ;
}
int query(char *str) // 查询有多少个字符串是 T 的前缀
{
int p = 0, res = 0;
for (int i = 0; str[i]; i ++ )
{
int u = str[i] - ‘a‘;
if (!son[p][u]) return res;
p = son[p][u];
res += cnt[p];
}
return res;
}
int main() {
scanf("%d%d", &n, &m);
while (n -- ){
scanf("%s", str);
insert(str);
}
while (m -- ) {
scanf("%s", str);
printf("%d\n", query(str));
}
return 0;
}
原文:https://www.cnblogs.com/huhu555/p/14665118.html