c语言sscanf函数的用法是什么
304
2022-08-29
LeetCode-208. Implement Trie (Prefix Tree)
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();trie.insert("apple");trie.search("apple"); // returns truetrie.search("app"); // returns falsetrie.startsWith("app"); // returns truetrie.insert("app"); trie.search("app"); // returns true
Note:
You may assume that all inputs are consist of lowercase lettersa-z.All inputs are guaranteed to be non-empty strings.
题解:
class Trie { struct trieTree { trieTree* child[26]; bool isWord; bool hasPrefix; trieTree() { for (int i = 0; i < 26; i++) { child[i] = NULL; } isWord = false; hasPrefix = false; } }; trieTree *root;public: /** Initialize your data structure here. */ Trie() { root = new trieTree(); } /** Inserts a word into the trie. */ void insert(string word) { trieTree *t = root; for (int i = 0; i < word.size(); i++) { if (t->child[word[i]- 'a'] == NULL) { t->child[word[i] - 'a'] = new trieTree(); t->hasPrefix = true; } t = t->child[word[i] - 'a']; } t->isWord = true; t->hasPrefix = true; } /** Returns if the word is in the trie. */ bool search(string word) { trieTree *t = root; for (int i = 0; i < word.size(); i++) { if (t->child[word[i]- 'a'] == NULL) { return false; } t = t->child[word[i] - 'a']; } return t->isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { trieTree *t = root; for (int i = 0; i < prefix.size(); i++) { if (t->child[prefix[i]- 'a'] == NULL) { return false; } t = t->child[prefix[i] - 'a']; } return t->hasPrefix; }};
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~