[LeetCode]Implement Trie (Prefix Tree)
2015-07-24 15:22
344 查看
解题思路:
字典树,每个节点应该包括 isWord(是否有单词在这个node结束) ,freq (词频统计,这里没用到),child(包含26个child)
1,insert操作:遍历word每一个字符,如果cur对应的child为空,就new一个新的TrieNode,最后isWord = true;
2,search 和 startsWith都是调用searchTree这个方法;
3,searchTree第三个参数findPrefix用于判断是 搜索全单词,还是搜索前缀
searchTree逻辑
1,如果root为空,说明call这个searchTree的那个char不存在,返回false
2,如果*ch == ‘\0’ ,查询结束,如果findPrefix为真,则返回true,否则返回isWord
3,递归。
字典树,每个节点应该包括 isWord(是否有单词在这个node结束) ,freq (词频统计,这里没用到),child(包含26个child)
1,insert操作:遍历word每一个字符,如果cur对应的child为空,就new一个新的TrieNode,最后isWord = true;
2,search 和 startsWith都是调用searchTree这个方法;
3,searchTree第三个参数findPrefix用于判断是 搜索全单词,还是搜索前缀
searchTree逻辑
1,如果root为空,说明call这个searchTree的那个char不存在,返回false
2,如果*ch == ‘\0’ ,查询结束,如果findPrefix为真,则返回true,否则返回isWord
3,递归。
class TrieNode { public: vector<TrieNode *> child; int freq; bool isWord; char ch; // Initialize your data structure here. TrieNode():freq(0), isWord(false), child(vector<TrieNode*>(26, nullptr)), ch('\0'){ } }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(string word) { TrieNode* cur = root; for (int i = 0; i < word.length(); ++i){ int ind = word[i] - 'a'; if (cur->child[ind] == NULL){ cur->child[ind] = new TrieNode(); } cur = cur->child[ind]; } cur->isWord = true; } // Returns if the word is in the trie. bool search(string word) { return searchTree(word.c_str(), root, false); } bool searchTree(const char* ch, TrieNode *root, bool findPrefix){ if (root == NULL) return false; if (*ch == '\0') return findPrefix ? true : root->isWord; int ind = *ch - 'a'; return searchTree(ch+1, root->child[ind], findPrefix); } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) { return searchTree(prefix.c_str(), root, true); } private: TrieNode* root; }; // Your Trie object will be instantiated and called as such: // Trie trie; // trie.insert("somestring"); // trie.search("key");
相关文章推荐
- oracle登录错误(ORA-01033:ORACLE initialization or shutdown in progress
- Linux 内核中RAID5源码详解之守护进程raid5d
- java面试中注意的问题02
- POJ 2456 Aggressive cows 【二分】
- oracle序列的创建、删除和使用
- LeetCode237:Delete Node in a Linked List
- bzoj-1901 Dynamic Rankings
- pip安装使用详解
- Android LayoutInflater深度解析
- 微软向Win10 Build 10240推送两枚更新
- AngularJS学习笔记(一)
- 19岁少年重塑CPU,降低80%计算机功耗
- Java Heap sapce 与 Java PermGen space
- 新一代 Linux 文件系统 btrfs 简介
- Cache 在选择的几点思考
- poj 1068 Parencodings 模拟
- 嵌入在网站上Flash播放机(2)
- Mysql slow query log
- 在Unix系统中,主存索引节点和辅存索引节点从内容上比较有什么不同,为什么要设置主存索引节点?
- 斯坦福《机器学习》Lesson6感想———1、函数间隔和几何间隔