力扣648.单词替换
-
字典树
- 构建字典树
- 遍历每个字母判断操作
-
class Solution { struct Trie{ bool isEnd = false; Trie* next[26] = {0}; }; public: string replaceWords(vector<string>& dictionary, string sentence) { Trie* trie = new Trie(); for(auto& dict:dictionary) { Trie* node = trie; for(char c:dict) { if(node->next[c-'a'] == NULL) node->next[c -'a'] = new Trie(); node = node->next[c-'a']; } node->isEnd = true; } string result = ""; Trie* node = trie; int i = 0; while(i<sentence.size()) { //如果是字典中的字符串并且到结尾了 if(node->isEnd) { node = trie; while(sentence[i] != ' ' && i < sentence.size()) i ++; continue; } if(sentence[i] == ' ') { result += " "; node = trie; i++; continue; } //如果是不在字典中的单词 直接全部加到答案里 if(node->next[sentence[i] - 'a'] == NULL) { while(sentence[i] != ' ' && i < sentence.size()) { result += sentence[i]; i ++; } } //在字典中的单词 一个一个加 else if(node->next[sentence[i] - 'a'] != NULL) { result += sentence[i]; node = node->next[sentence[i] - 'a']; i++; } } return result; } };