劍指 Offer II Trie字首樹
阿新 • • 發佈:2022-03-31
062. 實現字首樹
class Trie { public: /** Initialize your data structure here. */ int son[100010][26],cnt[100010],idx=0; Trie() { memset(son,0,sizeof son); } /** Inserts a word into the trie. */ void insert(string word) { int p=0; for( char c: word) { int u=c-'a'; if(!son[p][u])son[p][u]=++idx; p=son[p][u]; } cnt[p]++; } /** Returns if the word is in the trie. */ bool search(string word) { int p=0; for(char c:word){ int u=c-'a'; if(!son[p][u])return false; p=son[p][u]; } return cnt[p]>0; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { int p=0; for(char c:prefix){ int u=c-'a'; if(!son[p][u])return false; p=son[p][u]; } return true; } };
063. 替換單詞
class Solution { public: int son[100010][26],cnt[100010],idx=0; void insert(string s) { int p=0; for(char c:s) { int u=c-'a'; if(!son[p][u])son[p][u]=++idx; p=son[p][u]; } cnt[p]++; } string check(string s) { string res; int p=0; for(char c:s) { int u=c-'a'; if(!son[p][u])break; res+=c; p=son[p][u]; if(cnt[p])return res; } if(cnt[p])return res; return ""; } string replaceWords(vector<string>& dictionary, string sentence) { for(auto s:dictionary)insert(s); stringstream ssin(sentence); string ans,word; while(ssin >>word) { //cout<<word<<"..."<<endl; string x=check(word); // cout<<x<<endl; if(x!="") { ans+=x; } else ans+=word; ans+=" "; } return ans.substr(0,ans.size()-1); } };