Given a dictionary of words, find all occurrences of the roots in the sentence and replace them with the root itself. If a word has multiple roots, replace it with the shortest one.
Input: dictionary = ["cat", "bat", "rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Here is the C++ implementation for the described problem:
#include <iostream>
#include <vector>
#include <sstream>
#include <unordered_map>
using namespace std;
class TrieNode {
public:
unordered_map<char, TrieNode*> children;
string word;
TrieNode() : word("") {}
};
class Trie {
private:
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode* node = root;
for(char ch : word) {
if(!node->children.count(ch)) {
node->children[ch] = new TrieNode();
}
node = node->children[ch];
}
node->word = word;
}
string searchPrefix(string word) {
TrieNode* node = root;
for(char ch : word) {
if(node->children.count(ch)) {
node = node->children[ch];
if(!node->word.empty()) { // If a word is found in the trie
return node->word;
}
} else {
break;
}
}
return word; // Return original word if no prefix found
}
};
class Solution {
public:
string replaceWords(vector<string>& dictionary, string sentence) {
Trie trie;
for(string root : dictionary) {
trie.insert(root);
}
stringstream ss(sentence);
string word;
string result = "";
while(ss >> word) {
if(!result.empty()) {
result += " ";
}
result += trie.searchPrefix(word);
}
return result;
}
};
// Helper function to print the solution
int main() {
vector<string> dictionary = {"cat", "bat", "rat"};
string sentence = "the cattle was rattled by the battery";
Solution solution;
string replacedSentence = solution.replaceWords(dictionary, sentence);
cout << replacedSentence << endl; // Output: "the cat was rat by the bat"
return 0;
}
O(D * L)
where D
is the number of dictionary words and L
is the maximum length of a dictionary word.N
and each word of maximum length L
, the prefix search operation will be O(N * L)
.Overall, the time complexity is O(D * L + N * L)
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?