[hihoCoder] Trie树
2015-06-07 16:44
120 查看
This is a application of the Trie data structure, with minor extension. The critical part in this problem is to count all the words that have a particualr prefix and the problem has given nice hints to make this extension.
Two functions require to be implemented: add a word to the Trie and search the Trie for all words with a particular prefix.
The code is as follows.
If you are not familiar with Trie, you may refer to this solution first to get the basic idea of it.
Two functions require to be implemented: add a word to the Trie and search the Trie for all words with a particular prefix.
The code is as follows.
If you are not familiar with Trie, you may refer to this solution first to get the basic idea of it.
#include <iostream> using namespace std; class TrieNode { public: int count; TrieNode* children[26]; TrieNode() { count = 0; for (int i = 0; i < 26; i++) children[i] = NULL; } }; class Dictionary { public: Dictionary() { root = new TrieNode(); } void insert(char* word) { TrieNode* run = root; for (int i = 0; word[i]; i++) { if (!(run -> children[word[i] - 'a'])) run -> children[word[i] - 'a'] = new TrieNode(); run = run -> children[word[i] - 'a']; run -> count++; } } int search(char* prefix) { TrieNode* run = root; for (int i = 0; prefix[i]; i++) { if (run) run = run -> children[prefix[i] - 'a']; else break; } if (!run) return false; return run -> count; } private: TrieNode* root; }; int main(void) { int dictSize; while (scanf("%d", &dictSize) != EOF) { Dictionary dictionary; char word[20]; for (int i = 0; i < dictSize; i++) { scanf("%s", word); dictionary.insert(word); } int querySize; scanf("%d", &querySize); char prefix[20]; for (int i = 0; i < querySize; i++) { scanf("%s", prefix); printf("%d\n", dictionary.search(prefix)); } } return 0; }
相关文章推荐
- codeforce Looksery Cup 2015 H Degenerate Matrix
- iOS开发UI高级—35核心动画(转场动画和组动画)
- js实现删除等其他操作弹出的提示框
- STM32第十二天AD转换
- 自定义View之onMeasure()
- Android视图绘制流程完全解析,带你一步步深入了解View(二)
- 单片机学习之路
- cf#306D. Regular Bridge(图论,构图)
- Nginx整合PHP原理
- iOS开发UI高级—33核心动画(基础动画)
- WinXP系统鼠标驱动出现问题导致点击无反应怎么办?
- iOS开发UI高级—34核心动画(关键帧动画)
- activiti学习(三)
- Activity四种状态
- iOS开发UI高级—32核心动画简介
- 每次打开Microsoft office word2010时都要显示安装配置文件的问题
- 二叉查找树
- 后端设计中特殊单元
- 四个机器学习一步一步入门约束波尔兹曼机RBM
- iOS开发UI高级—31CAlayer(自定义layer)