Last updated on October 5th, 2024 at 08:53 pm
Here, We see Replace Words LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Hash Table, Trie
Companies
Uber
Level of Question
Medium
Replace Words LeetCode Solution
Table of Contents
Problem Statement
In English, we have a concept called root, which can be followed by some other word to form another longer word – let’s call this word successor. For example, when the root “an” is followed by the successor word “other”, we can form a new word “another”.
Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.
Return the sentence after the replacement.
Example 1:
Input: dictionary = [“cat”,”bat”,”rat”], sentence = “the cattle was rattled by the battery”
Output: “the cat was rat by the bat”
Example 2:
Input: dictionary = [“a”,”b”,”c”], sentence = “aadsfasf absbs bbab cadsfafs”
Output: “a a b c”
1. Replace Words LeetCode Solution C++
class Solution { public: string replaceWords(vector<string>& dictionary, string sentence) { string ans=""; unordered_set<string>s(dictionary.begin(),dictionary.end()); string x=""; for(int i=0;i<sentence.size();) { if(sentence[i]==' ') { ans+=x; ans+=' '; x=""; } else { x+=sentence[i]; if(s.find(x)!=s.end()) { while(i<sentence.size() && sentence[i]!=' ') { i++; } ans+=x; x=""; continue; } } i++; } if(x.size()!=0)ans+=x; return ans; } };
2. Replace Words Solution Java
class Solution { public String replaceWords(List<String> dictionary, String sentence) { Set<String> set = new HashSet(); for (String root: dictionary) set.add(root); StringBuilder ans = new StringBuilder(); String word[] = sentence.split(" "); for (int j=0;j<word.length;j++) { String prefix = ""; for (int i=1; i<=word[j].length();++i) { prefix = word[j].substring(0, i); if (set.contains(prefix)) break; } if(ans.length()>0) ans.append(" "); ans.append(prefix); } return ans.toString(); } }
3. Replace Words Solution JavaScript
var replaceWords = function(dictionary, sentence) { let wordArr = sentence.split(" "); wordArr = wordArr.map(w => { for(let i = 0; i <= dictionary.length - 1; i++) { if (w.indexOf(dictionary[i]) === 0) { w = dictionary[i]; } } return w; }) return wordArr.reduce((str, word) => str += `${word} `, "").trim(); };
4. Replace Words Solution Python
class Solution(object): def replaceWords(self, dictionary, sentence): setenceAsList = sentence.split(" ") for i in range(len(setenceAsList)): for j in dictionary: if setenceAsList[i].startswith(j): setenceAsList[i] = j return " ".join(setenceAsList)