国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Leetcode 208. Implement Trie (Prefix Tree)

2019-11-09 19:50:40
字體:
供稿:網(wǎng)友

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很方便快速。每個節(jié)點(diǎn)包括26個指針數(shù)組,對應(yīng)26個字母,如果child[0]不為空,表示這個字母存在,否則沒這個字符;還有是否是單詞結(jié)尾的標(biāo)志符。 2. 如何insert? 需要對單詞從左往右dfs遍歷,比如:”bat”,首先看trie根節(jié)點(diǎn)指向的26個child的child[1]是否存在(不存在,用NULL表示),存在就進(jìn)入下一個層次,不存在則需要新建一個node,并讓child[1]指向這個節(jié)點(diǎn)。 3. 如何搜索?搜索和insert很類似,都是通過dfs一層一層的往下找,某個位置如果沒指針,表示沒找到;最后位置如果沒有isWord表示也沒有。這里就顯示單詞結(jié)尾符號的用處了! 4. 如何startswith?比如:查找是否含有以ab開頭的單詞。也是搜索,不過不需要判斷單詞結(jié)尾即可!

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); */
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 华阴市| 金寨县| 郴州市| 阜宁县| 华容县| 晋州市| 长沙县| 许昌市| 从江县| 丹阳市| 高淳县| 上饶市| 射洪县| 师宗县| 宝山区| 庆云县| 嘉义市| SHOW| 蒙山县| 咸丰县| 将乐县| 阜阳市| 阿图什市| 介休市| 申扎县| 始兴县| 静安区| 鱼台县| 台北县| 抚顺市| 田阳县| 康定县| 伊宁市| 台南县| 鄂托克前旗| 海林市| 哈密市| 阿鲁科尔沁旗| 嘉定区| 百色市| 荥经县|