From 8e901b63b94d0bf3677916e09ac16d552c410d5b Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Fri, 7 Jun 2024 15:18:39 +0530 Subject: [PATCH] Create 648. Replace Words --- 648. Replace Words | 98 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 648. Replace Words diff --git a/648. Replace Words b/648. Replace Words new file mode 100644 index 0000000..9c05ccf --- /dev/null +++ b/648. Replace Words @@ -0,0 +1,98 @@ +class TrieNode { +public: + TrieNode* children[26]; + bool isEndOfWord; + TrieNode() { + isEndOfWord = false; + for (int i = 0; i < 26; ++i) { + children[i] = nullptr; + } + } +}; + +class Trie { +public: + TrieNode* root; + Trie() { + root = new TrieNode(); + } + + void insert(string word) { + TrieNode* curr = root; + for (char c : word) { + int index = c - 'a'; + if (!curr->children[index]) { + curr->children[index] = new TrieNode(); + } + curr = curr->children[index]; + } + curr->isEndOfWord = true; + } + + bool search(string word) { + TrieNode* curr = root; + for (char c : word) { + int index = c - 'a'; + if (!curr->children[index]) { + return false; + } + curr = curr->children[index]; + } + return curr->isEndOfWord; + } + + bool startsWith(string prefix) { + TrieNode* curr = root; + for (char c : prefix) { + int index = c - 'a'; + if (!curr->children[index]) { + return false; + } + curr = curr->children[index]; + } + return true; + } + + string findShortedPrefix(string word) { + TrieNode* curr = root; + for (int i = 0; i < word.length(); ++i) { + int index = word[i] - 'a'; + if (!curr->children[index]) { + return word; + } + curr = curr->children[index]; + if (curr->isEndOfWord) { + return word.substr(0, i + 1); + } + } + return word; + } +}; + +class Solution { +public: + string replaceWords(vector& dictionary, string sentence) { + Trie trie; + for (string& word : dictionary) { + trie.insert(word); + } + vector tokens; + string token; + for (char c : sentence) { + if (c == ' ') { + tokens.push_back(token); + token = ""; + } else { + token += c; + } + } + tokens.push_back(token); + string result = ""; + for (string& token : tokens) { + string prefix = trie.findShortedPrefix(token); + result += prefix + " "; + } + result.pop_back(); // Remove trailing space + return result; + } +};