国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 蒲江县| 鄱阳县| 渑池县| 临邑县| 叙永县| 偃师市| 合川市| 嵊州市| 焦作市| 平乡县| 金乡县| 岳西县| 广宗县| 江山市| 靖安县| 博客| 南阳市| 眉山市| 永德县| 织金县| 和硕县| 尼勒克县| 巴林左旗| 苗栗市| 巴楚县| 古蔺县| 广饶县| 玉环县| 冕宁县| 抚远县| 石嘴山市| 五峰| 沁水县| 赤水市| 宜兰市| 汉中市| 从化市| 灵宝市| 苗栗县| 莱阳市| 淮北市|