1. 问题:
1.1 问题描述:
在英语中,我们有一个叫做 词根(root)的概念,它可以跟着其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。
现在,给定一个由许多词根组成的词典和一个句子。你需要将句子中的所有继承词用词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。
你需要输出替换之后的句子。
1.2 示例:
输入:dict(词典) = ["cat", "bat", "rat"] sentence(句子) = "the cattle was rattled by the battery"
输出:"the cat was rat by the bat"
提示:
输入只包含小写字母。
1 <= dict.length <= 1000
1 <= dict[i].length <= 100
1 <= 句中词语数 <= 1000
1 <= 句中词语长度 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/replace-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 思路:
典型的字典树应用。
3. C++代码:
class trie{
private:
bool isend;
trie* next[26];
public:
trie(){
isend = false;
for(int i=0;i<26;i++){
next[i] = NULL;
}
}
void insert(string str){
trie* node = this;
int i;
for(i=0;i<str.size();i++){
if(node->next[str[i]-'a']==NULL){
node->next[str[i]-'a'] = new trie();
}
node = node->next[str[i]-'a'];
}
node->isend = true;
}
string search(string str){
trie* node = this;
string res;
int i;
for(i=0;i<str.size();i++){
if(node->next[str[i]-'a']==NULL){
return "";
}
else{
node = node->next[str[i]-'a'];
}
res += str[i];
if(node->isend==true){
return res;
}
}
return "";
}
};
class Solution {
public:
string replaceWords(vector<string>& dict, string sentence) {
string result;
trie root;
int i;
for(i=0;i<dict.size();i++){
root.insert(dict[i]);
}
stringstream s1(sentence);
string temp;
while(s1 >> temp){
if(root.search(temp)!=""){
result += root.search(temp);
result += " ";
}
else{
result += temp;
result += " ";
}
}
result = result.substr(0, result.size()-1);
return result;
}
};