LeetCode 648 Replace Words
概述
https://leetcode.com/problems/replace-words/
基于前缀树的实现
在将句子分割成单词时,别忘记在循环结束后收集最后一个单词。
class Solution {
public:
class Node {
public:
Node* children[26];
bool end = false;
Node() : children() {}
};
string replaceWords(vector<string>& dictionary, string sentence) {
auto root = new Node;
for (auto& word : dictionary) {
auto node = root;
for (auto c : word) {
if (!node->children[c - 'a']) {
node->children[c - 'a'] = new Node;
}
node = node->children[c - 'a'];
}
node->end = true;
}
vector<string> words;
string t;
for (auto c : sentence) {
if (c == ' ') {
words.push_back(t);
t = "";
} else {
t += c;
}
}
words.push_back(t);
string res;
for (auto& word : words) {
auto node = root;
string prefix;
for (auto c : word) {
if (node->children[c - 'a']) {
prefix += c;
node = node->children[c - 'a'];
if (node->end) break;
} else {
prefix = word;
break;
}
}
res += prefix + " ";
}
res.pop_back();
return res;
}
};
Links: leetcode-648-replace-words