一、题目描述
二、解题思路
用双指针法切割字符串,得到每一个单词,然后开始遍历字典
- 首先判断单词首字母和字典当前元素的首字母是否相等,相等继续进行下一步,否则肯定不是
- 判断当前单词的前缀是否等于字典当前元素
- 如果以上两个条件都满足,就把单词替换成词根,注意这个动作完成后不能直接
break
因为有可能存在继承词有许多可以形成词根的情况,我们需要找到最短的,比如:["catt","cat","bat","rat"] "the cattle was rattled by the battery"
- 对于
cattle
,遇见catt
时,被替换成catt
;第二次变成catt
的cattle
与cat
比较的时候会被替换成cat
。如果第一次被替换成catt
就break
掉了的话就无法被替换成cat
- 对于
三、解题代码
class Solution {
public:
string replaceWords(vector<string>& dict, string sentence) {
string sln = "";
size_t l = 0, r = 0;
for(; l < sentence.size(); l++){
for(; r < sentence.size() && sentence[r] != ' '; r++);
auto cur_word = sentence.substr(l, r - l);
for(size_t i = 0; i < dict.size(); i++)
if((cur_word[0] == dict[i][0]) && (cur_word.substr(0, dict[i].size()) == dict[i])) cur_word = dict[i];
sln += cur_word + " ";
l = r++;
}
return sln.substr(0, sln.size() - 1);
}
};