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

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

Leetcode 208. Implement Trie (Prefix Tree)

2019-11-09 19:17:38
字體:
供稿:網(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é)點包括26個指針數(shù)組,對應(yīng)26個字母,如果child[0]不為空,表示這個字母存在,否則沒這個字符;還有是否是單詞結(jié)尾的標(biāo)志符。 2. 如何insert? 需要對單詞從左往右dfs遍歷,比如:”bat”,首先看trie根節(jié)點指向的26個child的child[1]是否存在(不存在,用NULL表示),存在就進(jìn)入下一個層次,不存在則需要新建一個node,并讓child[1]指向這個節(jié)點。 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ā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 宜章县| 凤庆县| 剑川县| 永吉县| 江油市| 黄大仙区| 正安县| 茶陵县| 宁阳县| 郓城县| 漯河市| 通州市| 府谷县| 日土县| 宝兴县| 上高县| 玛纳斯县| 衡东县| 仪陇县| 施秉县| 温宿县| 营口市| 汝阳县| 宝应县| 玉环县| 民县| 鹤峰县| 陆河县| 舞钢市| 长春市| 阿巴嘎旗| 交城县| 弥渡县| 太谷县| 昭觉县| 丰宁| 灵寿县| 图们市| 始兴县| 绵阳市| 宿松县|