题目:
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”); // 返回 true
trie.search(“app”); // 返回 false
trie.startsWith(“app”); // 返回 true
trie.insert(“app”);
trie.search(“app”); // 返回 true
说明:
你可以假设所有的输入都是由小写字母 a-z 构成的。
保证所有输入均为非空字符串。
解题思路
这道题如果直接用vector来处理的话,将放入的数据放入一个vector<string>中自然是一种思路,具体代码如下:
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
vector<string> data(0);
}
/** Inserts a word into the trie. */
void insert(string word) {
this->data.push_back(word);
return;
}
/** Returns if the word is in the trie. */
bool search(string word) {
for (auto x : this->data)
{
if (x == word)
{
return true;
}
}
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix)
{
int len = prefix.size();
for (auto x : this->data)
{
if (x.substr(0, len) == prefix)
return true;
}
return false;
}
private:
vector<string> data;
};
/**
* 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);
*/
但是提交上述代码之后会出现超出时间限制的情况,因此我们需要改进一下这个数据结构,利用树结构来构造即可,将每个单词都当做一个节点,具体代码如下:
struct TrieNode
{
public:
bool flag;
TrieNode* childnode[26] = {nullptr};
TrieNode() : flag( false ) {};
};
class Trie
{
private:
TrieNode* root;
public:
/** Initialize your data structure here. */
Trie()
{
root = new TrieNode();
};
/** Inserts a word into the trie. */
void insert(string word)
{
auto node = root;
int index;
for (auto x : word)
{
index = x - 'a';
if (node->childnode[index] == nullptr)
{
node->childnode[index] = new TrieNode();
}
node = node->childnode[index];
}
node->flag = true;
}
/** Returns if the word is in the trie. */
bool search(string word)
{
int index;
auto node = root;
for (auto x : word)
{
index = x - 'a';
if (node->childnode[index] == nullptr) return false;
node = node->childnode[index];
}
return node->flag;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix)
{
auto node = root;
int index;
for (auto x : prefix)
{
index = x - 'a';
if (node->childnode[index] == nullptr) return false;
node = node->childnode[index];
}
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);
*/