Implement a trie with insert, search, and startsWith methods.
Note: You may assume that all inputs are consist of lowercase letters a-z.
s思路: 1. trie,前綴樹。用來搜索string很方便快速。每個節點包括26個指針數組,對應26個字母,如果child[0]不為空,表示這個字母存在,否則沒這個字符;還有是否是單詞結尾的標志符。 2. 如何insert? 需要對單詞從左往右dfs遍歷,比如:”bat”,首先看trie根節點指向的26個child的child[1]是否存在(不存在,用NULL表示),存在就進入下一個層次,不存在則需要新建一個node,并讓child[1]指向這個節點。 3. 如何搜索?搜索和insert很類似,都是通過dfs一層一層的往下找,某個位置如果沒指針,表示沒找到;最后位置如果沒有isWord表示也沒有。這里就顯示單詞結尾符號的用處了! 4. 如何startswith?比如:查找是否含有以ab開頭的單詞。也是搜索,不過不需要判斷單詞結尾即可!
struct node{ node* child[26]; bool isWord; node(){ for(int i=0;i<26;i++) child[i]=NULL; isWord=false; } };class Trie {PRivate: node* root;public: /** Initialize your data structure here. */ Trie() { root=new node(); } /** Inserts a word into the trie. */ void insert(string word) { node* cur=root; for(int i=0;i<word.size();i++){ int idx=word[i]-'a'; if(!cur->child[idx]){//沒有這個字母 cur->child[idx]=new node(); } cur=cur->child[idx]; } cur->isWord=true; } /** Returns if the word is in the trie. */ bool search(string word) { node* cur=root; for(int i=0;i<word.size();i++){ int idx=word[i]-'a'; if(!cur->child[idx]){//沒有這個字母 return false; } cur=cur->child[idx]; } return cur->isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { node* cur=root; for(int i=0;i<prefix.size();i++){ int idx=prefix[i]-'a'; if(!cur->child[idx]){//沒有這個字母 return false; } cur=cur->child[idx]; } 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); */新聞熱點
疑難解答