LeetCode#208 Implement Trie-Prefix Tree
1、C++使得struct也能作为类使用,可以包含函数。同时struct可以有自己的构造函数
其定义方法为(1)
struct TNode{
char key;
map<char, TNode*> NextMap;
};
实际上,可以在定义的同时创建一个对象,如(2)
struct TNode{
char key;
map<char, TNode*> NextMap;
}Node;
除此之外,也利用typedef来定义(3)
typedef struct Tnode{
char key;
map<char, struct Tnode*> NextMap;
}TNode;
此时效果同(1)。之后利用TNode创建对象即可。
2、构造函数的另一种写法:
TNode(char letter) : key(letter), count(0), order(0){}
等同于
TNode(char letter){
key = letter;
count = order = 0;
}
3、构造函数不需要提供返回值,但若调用了私有类/结构,同样需要new一个
class Trie {
private:
//each node
//declaim struct type and its alias
struct TNode{
char key;
map<char, TNode*> NextMap;
int count;
int order;
TNode(char letter) : key(letter), count(0), order(0){}
//below is fine
// TNode(char letter){
// key = letter;
// count = order = 0;
// }
};
//below is fine as well
// typedef struct trieNode{
// ...
// }TNode;
TNode* rootPtr;
int orderIndex;
public:
/** Initialize your data structure here. */
Trie() {
rootPtr = new TNode(0);
orderIndex = 1;
}
/** Inserts a word into the trie. */
void insert(string word) {
TNode* innerPtr = rootPtr;
for(auto ch : word){
auto it = innerPtr->NextMap.find(ch);
//a new node, ergodic
if(it == innerPtr->NextMap.end()){
innerPtr->NextMap[ch] = new TNode(ch);
innerPtr = innerPtr->NextMap[ch];
}
//use node exists && ergodic
else{
innerPtr = it->second;
}
}
//empty or end, deal with c&o
innerPtr->count++;
innerPtr->order = orderIndex++;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TNode* innerPtr = rootPtr;
for(auto ch : word){
auto it = innerPtr->NextMap.find(ch);
if(it == innerPtr->NextMap.end()){
return false;
}
innerPtr = it->second;
}
return (innerPtr->count) ? true : false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TNode* innerPtr = rootPtr;
for(auto ch : prefix){
auto it = innerPtr->NextMap.find(ch);
if(it == innerPtr->NextMap.end()){
return false;
}
innerPtr = it->second;
}
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);
*/