题目描述
解题思路
题目大意:
统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀)。
对每个节点维护cnt,记录经过此节点的次数,然后访问前缀所在节点的cnt即可。
参考代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Trie {
Trie* next[26];
int cnt;
} root;
int getid(char c) { return c - 'a'; }
void insert(char* s) {
Trie* head = &root;
while (*s) {
int id = getid(*s++);
if (head->next[id] == NULL)
head->next[id] = (Trie*) calloc(1, sizeof(Trie));
head = head->next[id];
(head->cnt)++;
}
}
int search(char* s) {
Trie* head = &root;
while (*s) {
int id = getid(*s++);
if (head->next[id] == NULL) return 0;
head = head->next[id];
}
return head->cnt;
}
int main() {
char s[15];
while (gets(s), *s) insert(s);
while (gets(s)) printf("%d\n", search(s));
return 0;
}