- 题目
实现一个trie树,要求实现addWord, removeWord, hasWorld, enumulateWord四个函数
思路:leetcode 208 变形
/*
* @lc app=leetcode id=208 lang=cpp
*
* [208] Implement Trie (Prefix Tree)
*
* https://leetcode.com/problems/implement-trie-prefix-tree/description/
*
* algorithms
* Medium (39.88%)
* Likes: 1838
* Dislikes: 35
* Total Accepted: 199.8K
* Total Submissions: 494.5K
* Testcase Example: '["Trie","insert","search","search","startsWith","insert","search"]\n[[],["apple"],["apple"],["app"],["app"],["app"],["app"]]'
*
* Implement a trie with insert, search, and startsWith methods.
*
* Example:
*
*
* Trie trie = new Trie();
*
* trie.insert("apple");
* trie.search("apple"); // returns true
* trie.search("app"); // returns false
* trie.startsWith("app"); // returns true
* trie.insert("app");
* trie.search("app"); // returns true
*
*
* Note:
*
*
* You may assume that all inputs are consist of lowercase letters a-z.
* All inputs are guaranteed to be non-empty strings.
*
*
*/
代码
class Trie
{
public:
struct Node
{
bool is_end;
Node *son[26];
Node()
{
is_end = false;
for (int i = 0; i < 26; i ++ ) son[i] = NULL;
}
}*root; // define a return type
//Error: error: new types may not be defined in a return type
Trie()
{
root = new Node();
}
void insert(string word)
{
auto p = root;
for (auto c: word)
{
int u = c - 'a';
if (p->son[u] == NULL) p->son[u] = new Node();
p = p->son[u]; //这里不是else
}
p->is_end = true;
}
bool search(string word)
{
auto p = root;
for (auto c: word)
{
int u = c - 'a';
if (p->son[u] == NULL) return false;
else p = p->son[u];
}
return p->is_end;
}
bool startsWith(string prefix)
{
auto p = root;
for (auto c: prefix)
{
int u = c - 'a';
if (p->son[u] == NULL) return false;
else p = p->son[u];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/