#include<iostream> #include<string> #include<algorithm> using namespace std; class Node{ public: Node *next[26]; bool isend; Node(){ for(int i=0;i<26;i++){ next[i]=NULL; } isend=false; } ~Node(){} }; class Trie { public: /** Initialize your data structure here. */ Node *root; Trie() { root=new Node(); } /** insts a word into the trie. */ void inst(string word) { Node *p=root; for(int i=0;i<word.size();i++){ if(!p->next[word[i]-‘a‘]) p->next[word[i]-‘a‘]=new Node(); p=p->next[word[i]-‘a‘]; } p->isend=true; } /** Returns if the word is in the trie. */ bool se(string word) { Node *p=root; for(int i=0;i<word.size();i++){ if(!p->next[word[i]-‘a‘]) return false; p=p->next[word[i]-‘a‘]; } return p->isend; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { Node *p=root; for(int i=0;i<prefix.size();i++){ if(!p->next[prefix[i]-‘a‘]) return false; p=p->next[prefix[i]-‘a‘]; } return true; } }; int main(void){ Trie *trie=new Trie(); trie->inst("apple"); cout<<trie->se("apple")<<‘ ‘; // 返回 true cout<<trie->se("app")<<‘ ‘; // 返回 false cout<<trie->startsWith("app")<<‘ ‘; // 返回 true trie->inst("app"); cout<<trie->se("app")<<‘ ‘; // 返回 true return 0; } /** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->inst(word); * bool param_2 = obj->se(word); * bool param_3 = obj->startsWith(prefix); */
原文:https://www.cnblogs.com/programyang/p/11279937.html