本来感觉没什么难度的,和之前那道LRU差不多,结果看了题解……emmm只有我真的写了个树的结构体吗…………
class Trie {
public:
struct TreeNode{
char val;
map<char,TreeNode*> children;
TreeNode() : val(0) {}
TreeNode(char x) : val(x) {}
};
TreeNode* root;
Trie() {
root=new TreeNode();
}
void insert(string word) {
int loc=0;
TreeNode* now=root;
while(now->children[word[loc]]){
now=now->children[word[loc]];
loc++;
}
while(loc<word.size()){
TreeNode* newnode=new TreeNode(word[loc]);
now->children[word[loc]]=newnode;
now=newnode;
loc++;
}
TreeNode* newnode=new TreeNode('0');
now->children['0']=newnode;
}
bool search(string word) {
TreeNode* now=root;
for(int i=0;i<word.size();i++){
if(now->children.find(word[i])==now->children.end()) return 0;
else now=now->children[word[i]];
}
if(now->children['0']) return 1;
return 0;
}
bool startsWith(string prefix) {
TreeNode* now=root;
for(int i=0;i<prefix.size();i++){
if(now->children.find(prefix[i])==now->children.end()) return 0;
else now=now->children[prefix[i]];
}
return 1;
}
};
/**
* 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);
*/
总之写的好像有些跑题了,好吧看来这题和LRU还是有不同的,