Vowel Spellchecker
Here’s a step-by-step guide to solving this problem:
Create Maps for Words: We’ll create three maps: one for the exact words, one for the lowercase version, and one for the version with vowels replaced with a special character (for handling vowel errors).
Process the Word List: Iterate through the wordlist to fill the above maps.
Handle Queries: For each query, we’ll check the three cases (exact match, capitalization, vowel errors) using the maps.
Here’s the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
| class Solution:
def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:
exact_words = {}
case_insensitive_words = {}
vowel_error_words = {}
# Process the word list
for word in wordlist:
exact_words[word] = word
# Handle capitalization
lower_word = word.lower()
if lower_word not in case_insensitive_words:
case_insensitive_words[lower_word] = word
# Handle vowel errors
vowel_pattern = ''.join(['*' if c in 'aeiouAEIOU' else c for c in lower_word])
if vowel_pattern not in vowel_error_words:
vowel_error_words[vowel_pattern] = word
# Process queries
result = []
for query in queries:
if query in exact_words:
result.append(exact_words[query])
continue
lower_query = query.lower()
if lower_query in case_insensitive_words:
result.append(case_insensitive_words[lower_query])
continue
vowel_query_pattern = ''.join(['*' if c in 'aeiouAEIOU' else c for c in lower_query])
if vowel_query_pattern in vowel_error_words:
result.append(vowel_error_words[vowel_query_pattern])
continue
result.append("") # No match found
return result
|
Key Takeaways
- We created three maps to handle the three different cases.
- We preprocessed the wordlist and then handled each query efficiently using these maps.
- This code handles capitalization and vowel errors separately to achieve the desired precedence rules.
- The time complexity is O(N * K), where N is the total number of words in both the wordlist and queries, and K is the maximum length of a word. The space complexity is also O(N * K).