LC 648. 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:
- The input will only have lower-case letters.
- 1 <= dict words number <= 1000
- 1 <= sentence words number <= 1000
- 1 <= root length <= 100
- 1 <= sentence words length <= 1000
Runtime: 64 ms, faster than 45.77% of C++ online submissions for Replace Words.
#include <vector>
#include <string>
using namespace std;
class TrieNode{
public:
string word;
TrieNode* children[26];
TrieNode(){
for(int i=0; i<26; i++) children[i] = nullptr;
word = "";
}
};
class Trie{
public:
TrieNode* root;
Trie() {
root = new TrieNode();
}
void buildtrie(vector<string>& words){
for(int i=0; i<words.size(); i++){
TrieNode* tmp = root;
for(int j=0; j<words[i].size(); j++){
int idx = words[i][j] - 'a';
if(!tmp->children[idx]) tmp->children[idx] = new TrieNode();
tmp = tmp->children[idx];
}
tmp->word = words[i];
}
}
string hasprefix(string word){
TrieNode* tmp = root;
string prefix = "";
//cout << word << endl;
for(int i=0; i<word.size(); i++){
int idx = word[i] - 'a';
//cout << word << " " << idx << endl;
if(!tmp->children[idx]) return prefix;
tmp = tmp->children[idx];
if(tmp->word != ""){
//cout << prefix << endl;
prefix = tmp->word;
break;
}
}
return prefix;
}
};
class Solution {
public:
string replaceWords(vector<string>& dict, string sentence) {
Trie trie = Trie();
trie.buildtrie(dict);
vector<int> spaceidx;
for(int i=0; i<sentence.size(); i++){
if(sentence[i] == ' ') spaceidx.push_back(i);
}
vector<string> sent_vec;
int idx = 0;
if(spaceidx.size() == 0){
sent_vec.push_back(sentence);
}else{
for(int i=0; i<spaceidx.size(); i++){
sent_vec.push_back(sentence.substr(idx, spaceidx[i] - idx));
idx = spaceidx[i] + 1;
}
}
//for(auto x : spaceidx) cout << x << endl;
sent_vec.push_back(sentence.substr(idx));
//cout << sent_vec.size() << endl;
//for(auto s : sent_vec) cout << s << endl;
vector<string> retvec;
for(int i=0; i<sent_vec.size(); i++){
string tmpstr = trie.hasprefix(sent_vec[i]);
//cout << sent_vec[i] << endl;
if(tmpstr == "") retvec.push_back(sent_vec[i]);
else retvec.push_back(tmpstr);
}
string ret = "";
for(auto s : retvec) ret += s + " ";
return ret.substr(0,ret.size()-1);
}
};