题目
思路一 前缀哈希
把词根用一个集合存下来,再判断句子中每个词的每个前缀是否与词根相同,如果相同就返回前缀,否则返回word。
代码一
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
rootset = set(dictionary)
def replace(word):
for i in range(1,len(word)):
if(word[:i] in rootset):
return word[:i]
return word
return ' '.join(map(replace,sentence.split()))
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
words = sentence.split()
for i in range(len(words)):
for dic in dictionary:
if(words[i][0 : len(dic)] == dic):
words[i] = dic
return ' '.join(words)
思路二 前缀树
初始化字典树对象,变量为bool型isEnd和指针数组型next[26],实现insert和search函数。insert函数把字根插入字典树中。search函数在字典树中查询是否有词根是word的前缀,如果有就返回词根,否则返回word。主函数中,先把dictionary中的字符串插入到字典树中。再遍历sentence,获取每一个单词。如果遍历到空格就意味着上一个单词遍历完毕,就调用字典树的search函数,如果不是最后一个单词还需要添加空格。如果不是空格,就把这个字符添加到字符串tmp中。
代码二
class Trie{
private:
bool isEnd;
Trie* next[26];
public:
Trie(){
isEnd = false;
memset(next, 0, sizeof(next));
}
void insert(string word){
Trie* node = this;
for(char ch : word){
if(node -> next[ch - 'a'] == nullptr)
node -> next[ch - 'a'] = new Trie();
node = node -> next[ch - 'a'];
}
node -> isEnd = true;
}
string search(string word){
Trie* node = this;
string prefix = "";
for(char ch : word){
if(node -> isEnd) break;
if(node -> next[ch - 'a'] == nullptr)
return word;
prefix += ch;
node = node -> next[ch - 'a'];
}
return prefix;
}
};
class Solution {
public:
string replaceWords(vector<string>& dictionary, string sentence) {
Trie* tree = new Trie();
for(string root : dictionary)
tree -> insert(root);
int n = sentence.size();
string ans = "", tmp = "";
for(int i = 0; i <= n; i++){
if(i < n && sentence[i] != ' '){
tmp += sentence[i];
}else{
if(tmp != ""){
ans += tree -> search(tmp);
if(i < n) ans += " ";
}
tmp = "";
}
}
return ans;
}
};