Today's post brings out the awesome question from "problem of the day" on Leetcode. This code implements a solution to replace words in a sentence with their corresponding root words based on a given dictionary of root words. Let's break down the code step by step:
Class `Solution`
- `__init__(self)`: Initialises the Solution class with an empty dictionary `self.root` to store the trie structure and an empty dictionary `self.dictionaryDict` to store the dictionary words.
Method `createTrie(self, words)`
- `createTrie`: This method creates a trie data structure from the given words. It iterates through each character of each word in the input list `words`, adding each character to the trie. It marks the end of a word by appending `"*"` as a key in the trie.
Method `findPrefix(self, words)`
- `findPrefix`: This method finds the shortest prefix of the word in the trie that exists in the dictionary. It starts traversing the trie based on the characters in the input word. If it finds a `"*"` in the trie or reaches a point where the word doesn't exist in the trie, it checks if the current suffix (`suff`) exists in the dictionary. If it does, it returns the current suffix, otherwise, it returns `None`.
Method `replaceWords(self, dictionary, sentence)`
- `replaceWords`: This is the main method that replaces words in the given sentence with their corresponding root words from the dictionary. It first initializes an empty list `res` to store the result. Then, it iterates through each word in the dictionary, adding each word to `self.dictionaryDict` and creating a trie for each word using the `createTrie` method. Next, it splits the input sentence into a list of words using `split(' ')`. Then, for each word in the sentence, it finds the shortest prefix using the `findPrefix` method. If a prefix is found, it appends the prefix to the result list `res`, otherwise, it appends the original word. Finally, it joins the elements of `res` with spaces and returns the resulting sentence.
Time Complexity
- `createTrie`: Let `n` be the total number of characters in all words in the dictionary. The time complexity of creating the trie is O(n).
- `findPrefix`: Let `m` be the average length of the words in the dictionary and `l` be the length of the longest word. In the worst case, if all words have different prefixes, the time complexity is O(ml).
- `replaceWords`: Let `k` be the number of words in the dictionary and `p` be the number of words in the sentence. The time complexity is O(kml + p).
Space Complexity
- The space complexity is O(n + kml), where `n` is the total number of characters in all words in the dictionary, `k` is the number of words in the dictionary, `m` is the average length of the words in the dictionary, and `l` is the length of the longest word.
I hope you like my solution. Do give me an upvote.
Comments
Post a Comment