LeetCode 648. Replace Words 字典树练习

来源:互联网 发布:sql数据库管理下载 编辑:程序博客网 时间:2024/05/16 10:59

In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another.

Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with theroot forming it. If a successor has many roots can form it, replace it with the root with the shortest length.

You need to output the sentence after the replacement.

Example 1:

Input: dict = ["cat", "bat", "rat"]sentence = "the cattle was rattled by the battery"Output: "the cat was rat by the bat"

题意:用字典中存在的前缀代替句子中的单词,若有多个前缀可以表示单词,则选择最短的一个

用基础字典树即可解决,将字典中的前缀字符串存入字典树中,遍历每个句子的单词,找到最短的前缀返回即可

字典树结构:

struct Trie{int val;//表示此位置是否有前缀结束vector<Trie*> child;Trie():child(vector<Trie*>(26,NULL)),val(-1){}};

首先是字典树的创建(插入)过程,题目只要返回最短的前缀字符串,在插入时对于每一个字符串的最后一个字符节点的val设置为0表示此位置为结束位置。

void insert(string s,Trie* root){for(int i=0;i<s.size();i++){int num = s[i]-'a';if(root->child[num] == NULL){root->child[num] = new Trie();}root = root->child[num];        if(i!=s.size()-1&&root->val!=0)                root->val = 1;        else root->val = 0;//若此位置为结束位置,将val设置为0}}   

查找时,遇到val为0的字符节点就可以返回,这样就能保证返回的前缀为最短的,若字典树中不存在此单词的前缀,那么查找停止位置的val不等于0;

    string search(string s,Trie* root){string res = "";for(int i=0;i<s.size();i++){int num = s[i] -'a';if(root->child[num] == NULL)break;        root = root->child[num];    res += s[i];        if(root->val == 0)            return res;}        if(root->val == 0)        return res;        else return s;}


在分割句子时可以使用强大的stringstream,将sentence先读入字符串流中,以空格为标示分割句子,超级方便,字符串分割利器,还能类型转化等等:

string replaceWords(vector<string>& dict, string sentence) {        Trie *root = new Trie();        string res = "";        for(string s:dict)            insert(s,root);        stringstream ss(sentence);        string s;        int sign = 1;        while(ss>>s){            string temp = search(s,root);            if(sign!=1)                res += " ";            if(temp.empty())                res +=s;            else res +=temp;            sign++;        }        return res;    }



原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 写作业眼睛疼怎么办 发生火灾怎么办大班教案 大班健康发生火灾怎么办 学生上课不提问怎么办 入户通知单丢了怎么办 打架后还来找事该怎么办 着火了怎么办教案视频 电脑一小半黑屏怎么办 绝地求生闪退怎么办 win7没浏览器了怎么办 浏览器被删除了怎么办 把快捷方式删了怎么办 ie文件找不到了怎么办 ie文件不存在了怎么办 大学素质分不够怎么办 素拓学分不够怎么办 大学毕业之前素拓分拿不满怎么办 武汉幼儿医保卡怎么办 养老院护工欺老人怎么办 皮肤毛孔粗大有痘印痘坑怎么办 额头上毛孔大怎么办 额头皮肤毛孔大怎么办 脸部粗糙毛孔大怎么办 脸上有痘印毛孔粗大怎么办 毛孔粗大痘印怎么办 教官12123一直加载怎么办 教官嗓子哑了怎么办 喜欢上考场教官怎么办 跟教官打起来怎么办 车险贴丢了怎么办 大学不想军训该怎么办 职高军训不想去怎么办 上大学不想军训怎么办 收费站忘记带钱怎么办 孕妇咳得厉害怎么办 怀孕九个月咳嗽怎么办 门冬氨酸高怎么办 代理保证金不退怎么办 电脑游戏太大下载慢怎么办 四川百裕制药怎么办 想退出学校中层怎么办