标签:
Trie树概念相对简单。
如果是用于保存英文词典,时空效率都是不错的。
如果保存中文词典,对子节点的索引可能需要用一个哈希表来存。
在建树的过程中可以顺便统计特定前缀的单词数。
如果要求重复单词不重复统计,可以在插入前先查询一次。
本题的具体代码如下:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
typedef
struct trie_node {
trie_node * nodes[26];
int total;
bool leaf; // whether it‘s the end of a word
} trie, *ptrie;
using namespace std;
void trie_node_initialize(ptrie pnode) {
pnode->leaf = false;
pnode->total = 0;
for (int i = 0; i < 26; i++) {
pnode->nodes[i] = nullptr;
}
}
void trie_insert(ptrie proot, char *str) {
int len = strlen(str);
ptrie pcur = proot;
for (int i = 0; i < len; i++) {
int pos = str[i] - ‘a‘;
if (pcur->nodes[pos] == nullptr) {
ptrie pnew = new trie;
trie_node_initialize(pnew);
pcur->nodes[pos] = pnew;
}
pcur = pcur->nodes[pos];
pcur->total++;
}
pcur->leaf = true;
}
int trie_query(ptrie proot, char *str) {
int len = strlen(str);
ptrie pcur = proot;
for (int i = 0; i < len; i++) {
int pos = str[i] - ‘a‘;
if (pcur->nodes[pos] == nullptr) {
return 0;
}
pcur = pcur->nodes[pos];
}
return pcur->total;
}
void trie_destroy(ptrie proot) {
if (proot == nullptr) return;
for (int i = 0; i < 26; i++) {
trie_destroy(proot->nodes[i]);
}
delete proot;
}
int main() {
int n;
char str[15];
ptrie proot = new trie;
trie_node_initialize(proot);
cin >> n;
while (n--) {
cin >> str;
trie_insert(proot, str);
}
cin >> n;
while (n--) {
cin >> str;
printf("%d\n", trie_query(proot, str));
}
trie_destroy(proot);
return 0;
}
吐槽:突然知道为啥自己阿里面试没过了。当时面试官出了个几乎一模一样的题,我不假思索说用哈希表存字典。
标签:
原文地址:http://www.cnblogs.com/xblade/p/4442338.html