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

首頁 > 學院 > 開發設計 > 正文

Leetcode 208. Implement Trie (Prefix Tree)

2019-11-10 17:34:29
字體:
來源:轉載
供稿:網友

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); */
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 临颍县| 廊坊市| 乌兰浩特市| 大兴区| 和静县| 金门县| 富阳市| 西乌珠穆沁旗| 韶山市| 钟祥市| 濮阳市| 双鸭山市| 泰兴市| 陵川县| 衡阳县| 澄城县| 昆明市| 唐海县| 齐河县| 阜康市| 瓦房店市| 安岳县| 屏东县| 温宿县| 秦皇岛市| 上杭县| 铜山县| 宜城市| 安陆市| 张家港市| 晋城| 宁阳县| 集贤县| 津南区| 贵溪市| 河池市| 平昌县| 沂源县| 嫩江县| 南和县| 白朗县|