- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 47 lines of C++ from the credited upstream file 966.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 4 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<string> spellchecker(vector<string>& wordlist,4 vector<string>& queries) {5 vector<string> ans;6 unordered_map<string, string> dict;7 8 for (const string& word : wordlist) {9 dict.insert({word, word});10 dict.insert({lowerKey(word), word});11 dict.insert({vowelKey(word), word});12 }13 14 for (const string& query : queries)15 if (const auto it = dict.find(query); it != dict.cend())16 ans.push_back(it->second);17 else if (const auto it = dict.find(lowerKey(query)); it != dict.cend())18 ans.push_back(it->second);19 else if (const auto it = dict.find(vowelKey(query)); it != dict.cend())20 ans.push_back(it->second);21 else22 ans.push_back("");23 24 return ans;25 }26 27 private:28 string lowerKey(const string& word) {29 string s{"$"};30 for (const char c : word)31 s += tolower(c);32 return s;33 }34 35 string vowelKey(const string& word) {36 string s;37 for (const char c : word)38 s += isVowel(c) ? '*' : tolower(c);39 return s;40 }41 42 bool isVowel(char c) {43 static constexpr string_view kVowels = "aeiouAEIOU";44 return kVowels.find(c) != string_view::npos;45 }46};47