# 用Trie树统计以给定字符串为前缀的单词个数

10000ms 单点时限:
1000ms 内存限制:
256MB

### 描述

“你看，我们现在得到了这样一棵树，那么你看，如果我给你一个字符串ap，你要怎么找到所有以ap开头的单词呢？”小Hi又开始考校小Ho。

“唔…一个个遍历所有的单词？”小Ho还是不忘自己最开始提出来的算法。

“笨！这棵树难道就白构建了！”小Hi教训完小Ho，继续道：“看好了！”

“那么现在！赶紧去用代码实现吧！”小Hi如是说道

### 输出

```5
babaab
babbbaaaa
abba
aaaaabaa
babaababb
5
babb
baabaaa
bab
bb
bbabbaab```

```1
0
3
0
0```

``````#include <iostream>
#include <string>
using namespace std;

struct trieNode {
trieNode() : prefixLatterWords(0) {
for (size_t i = 0; i < 26; ++i) {
children[i] = NULL;
}
}

~trieNode() {
for (size_t i = 0; i < 26; ++i) {
if (children[i]) {
delete children[i];
children[i] = NULL;
}
}
}

int prefixLatterWords; //后续单词个数
trieNode *children[26];
};

class trie {
public:
trie() : root(new trieNode) {}

size_t Index(char c) {
return static_cast<size_t>(c % 26);
}

void insert(const string& word);

int countPrefix(const string& prefix);

public:
trieNode *root;
};

void trie::insert(const string& word) {
trieNode *cur = root;
for (size_t i = 0; i < word.size(); ++i) {
size_t idx = Index(word[i]);
if (!cur->children[idx]) {
cur->children[idx] = new trieNode;
}
cur = cur->children[idx];
++cur->prefixLatterWords;
}
}

int trie::countPrefix(const string& prefix) {
trieNode *cur = root;
for (size_t i = 0; i < prefix.size(); ++i) {
size_t idx = Index(prefix[i]);
if (!cur->children[idx]) {
return 0;
}
cur = cur->children[idx];
}
return cur->prefixLatterWords;
}

int main()
{
trie t;
int n, m;
cin >> n;
//建trie树
string word;
for (size_t i = 0; i < n; ++i) {
cin >> word;
t.insert(word);
}

cin >> m;
string prefix;
for (size_t i = 0; i < m; ++i) {
cin >> prefix;
cout << t.countPrefix(prefix) << endl;
}

//system("pause");
return 0;
}``````
原文作者：Trie树
原文地址: https://blog.csdn.net/ouyangjinbin/article/details/51210862
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。