648. 单词替换

该博客介绍了一个C++实现的解决方案,用于在给定的句子中替换单词。算法首先对字典进行排序,然后遍历句子,查找每个单词在字典中的最短前缀,从而实现单词替换。这个过程涉及到字符串处理和搜索技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

648. 单词替换

class Solution {
public:
    string replaceWords(vector<string>& dictionary, string sentence) {
        sort(dictionary.begin(), dictionary.end());
        vector<string> word;
        string temp;
        for (auto x : sentence)
        {
            if (x != ' ')
                temp.push_back(x);
            else
            {
                word.push_back(temp);
                temp.clear();
            }
        }
        word.push_back(temp);
        // cout << word.size() << endl;
        // for (auto x : word) cout << x << endl;
        string ret;
        for (auto x : word)
        {
            bool is_root = false;
            for (auto y : dictionary)
            {
                if (x.find(y) == 0)
                {
                    is_root = true;
                    ret += y;
                    break;
                }
            }
            if (!is_root)
                ret += x;    
            ret += " ";
        }
        ret.erase(ret.end() - 1);
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值