Leetcode 648. 单词替换(字典树)
是一个比较普通的字典树。细节应该算是比较多(?)
typedef pair<int,int> P; vector<P> flag[100007]; // first是字母,second是指向的序号 bool End[100007]; int cnt; //目前节点数 class Solution { public: string replaceWords(vector<string>& dictionary, string sentence) { //初始化 cnt=0; for (int i=0;i<1007;i++) flag[i].clear(); memset(End,0,sizeof(End)); int lim=dictionary.size(); for (int i=0;i<lim;i++){ int temp=dictionary[i].size(); int now=0; bool building=false; for (int j=0;j<temp;j++){ bool sign=false; if (building) goto here; for (int k=0;k<flag[now].size();k++) if (dictionary[i][j]==flag[now][k].first){ now=flag[now][k].second,sign=true; break; } if (sign) //不需要新建新节点 continue; //需要新建新节点 here:++cnt; P p; p.first=dictionary[i][j],p.second=cnt; flag[now].push_back(p); now=cnt; building=true; } End[now]=true; } lim=sentence.size(); int now=0; bool skip=false; bool forward=true; string ans; for (int i=0;i<lim;i++) if (sentence[i]==' '){ now=0; skip=false; forward=true; ans+=' '; } else if (!skip){ ans+=sentence[i]; int temp=flag[now].size(); if (forward){ forward=false; for (int j=0;j<temp;j++) if (sentence[i]==flag[now][j].first){ now=flag[now][j].second; forward=true; if (End[now]){ // return ans; skip=true; } break; } } } return ans; } }; //字典树


浙公网安备 33010602011771号