# [LeetCode] Replace Words 替换单词

In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another.

Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.

You need to output the sentence after the replacement.

Example 1:

Input: dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"


Note:

1. The input will only have lower-case letters.
2. 1 <= dict words number <= 1000
3. 1 <= sentence words number <= 1000
4. 1 <= root length <= 100
5. 1 <= sentence words length <= 1000

class Solution {
public:
string replaceWords(vector<string>& dict, string sentence) {
string res = "", t = "";
vector<vector<string>> v(26);
istringstream is(sentence);
sort(dict.begin(), dict.end(), [](string &a, string &b) {return a.size() < b.size();});
for (string word : dict) {
v[word[0] - 'a'].push_back(word);
}
while (is >> t) {
for (string word : v[t[0] - 'a']) {
if (t.substr(0, word.size()) == word) {
t = word;
break;
}
}
res += t + " ";
}
res.pop_back();
return res;
}
};

class Solution {
public:
class TrieNode {
public:
bool isWord;
TrieNode *child[26];
TrieNode(): isWord(false) {
for (auto &a : child) a = NULL;
}
};

string replaceWords(vector<string>& dict, string sentence) {
string res = "", t = "";
istringstream is(sentence);
TrieNode *root = new TrieNode();
for (string word : dict) {
insert(root, word);
}
while (is >> t) {
if (!res.empty()) res += " ";
res += findPrefix(root, t);
}
return res;
}

void insert(TrieNode* node, string word) {
for (char c : word) {
if (!node->child[c - 'a']) node->child[c - 'a'] = new TrieNode();
node = node->child[c - 'a'];
}
node->isWord = true;
}

string findPrefix(TrieNode* node, string word) {
string cur = "";
for (char c : word) {
if (!node->child[c - 'a']) break;
cur.push_back(c);
node = node->child[c - 'a'];
if (node->isWord) return cur;
}
return word;
}
};

Implement Trie (Prefix Tree)

https://discuss.leetcode.com/topic/97203/trie-tree-concise-java-solution-easy-to-understand

LeetCode All in One 题目讲解汇总(持续更新中...)

 微信打赏 Venmo 打赏
posted @ 2017-08-24 15:39  Grandyang  阅读(5938)  评论(0编辑  收藏  举报