leetcode---Implement Trie (Prefix Tree)---Trie树
2016-11-21 22:00
363 查看
Implement a trie with
insert,
search, and
startsWithmethods.
class TrieNode { public: // Initialize your data structure here. bool isLeaf; TrieNode *childs[26]; TrieNode() { isLeaf = false; memset(childs, 0, sizeof(childs)); } }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(string word) { int i = 0; int n = word.size(); TrieNode *p = root; while(i < n) { int j = word[i] - 'a'; if(p->childs[j] == NULL) p->childs[j] = new TrieNode(); p = p->childs[j]; i++; } p->isLeaf = true; } // Returns if the word is in the trie. bool search(string word) { TrieNode *p = root; int n = word.size(); if(n == 0) return true; int i = 0; while(i < n) { int j = word[i] - 'a'; if(p->childs[j] == NULL) return false; p = p->childs[j]; i++; } return p->isLeaf; } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) { TrieNode *p = root; int n = prefix.size(); if(n == 0) return true; int i = 0; while(i < n) { int j = prefix[i] - 'a'; if(p->childs[j] == NULL) return false; p = p->childs[j]; i++; } return true; } private: TrieNode* root; }; // Your Trie object will be instantiated and called as such: // Trie trie; // trie.insert("somestring"); // trie.search("key");
相关文章推荐
- LeetCode Implement Trie (Prefix Tree) (实现trie树3个函数:插入,查找,前缀)
- Leetcode Implement Trie (Prefix Tree)
- LeetCode -- Implement Trie (Prefix Tree)
- leetcode Implement Trie (Prefix Tree)
- [leetcode]Implement Trie (Prefix Tree)
- leetcode(208). Implement Trie (Prefix Tree)
- [LeetCode]Implement Trie (Prefix Tree)
- LeetCode - Implement Trie (Prefix Tree)
- LeetCode|Implement Trie (Prefix Tree)
- LeetCode- Implement Trie (Prefix Tree)
- [LeetCode] Implement Trie (Prefix Tree)
- Leetcode208-Implement Trie (Prefix Tree)
- 【Leetcode】Implement Trie (Prefix Tree)
- LeetCode-208 Implement Trie (Prefix Tree)
- LeetCode Implement Trie (Prefix Tree) 字典树/前缀树
- LeetCode: Implement Trie (Prefix Tree)
- [leetcode-208]Implement Trie (Prefix Tree)(java)
- leetcode 208: Implement Trie (Prefix Tree)
- LeetCode Implement Trie (Prefix Tree)
- [LeetCode] Implement Trie (Prefix Tree)