This problem requires us to replace words in a sentence using a dictionary of root words. The goal is to ensure that each word in the sentence is replaced by the shortest root word from the dictionary that is a prefix of the word.
To solve this problem efficiently, we can break down the solution into the following steps:
- Tokenize the Sentence: Split the given sentence into individual words.
- Replace Words: For each word, check if any root word in the dictionary is a prefix of the word. Replace the word with the shortest root word that matches.
- Reconstruct the Sentence: Combine the modified words back into a sentence.
class Solution {
public:
string replaceWords(vector<string>& dict, string sent) {
// Step 1: Split the sentence into words
int n = sent.size();
int i = 0;
vector<string> v;
string temp;
while (i < n) {
if (sent[i] != ' ') {
temp += sent[i];
i++;
} else {
v.push_back(temp);
temp = "";
i++;
}
}
v.push_back(temp);
// Step 2: Replace words using the dictionary
for (const auto& root : dict) {
int sz = root.size();
for (int j = 0; j < v.size(); j++) {
string curr = v[j].substr(0, sz);
if (curr == root) {
v[j] = root;
}
}
}
// Step 3: Reconstruct the sentence
string res;
for (const auto& word : v) {
res += word + " ";
}
res.pop_back(); // Remove the trailing space
return res;
}
};
- We initialize an empty vector
v
to store individual words from the sentence and a temporary stringtemp
to build each word.
- We iterate through the sentence character by character. When we encounter a space, we add the current word to the vector
v
and resettemp
for the next word.
- For each root word in the dictionary, we check if it matches the prefix of any word in the vector
v
. If it does, we replace the word with the root word.
- We concatenate the words from the vector
v
into a single stringres
, adding a space between each word. Finally, we remove the trailing space.
This approach ensures an efficient replacement of words based on the given dictionary of root words.
If you found this solution helpful, please consider liking 👍 and upvoting ⬆️. Your support helps me to keep providing high-quality solutions.