LeetCode Solutions

966. Vowel Spellchecker

Time:

Space:

			

class Solution {
 public:
  vector<string> spellchecker(vector<string>& wordlist,
                              vector<string>& queries) {
    vector<string> ans;
    unordered_map<string, string> dict;

    for (const string& word : wordlist) {
      dict.insert({word, word});
      dict.insert({lowerKey(word), word});
      dict.insert({vowelKey(word), word});
    }

    for (const string& q : queries)
      if (dict.count(q))
        ans.push_back(dict[q]);
      else if (dict.count(lowerKey(q)))
        ans.push_back(dict[lowerKey(q)]);
      else if (dict.count(vowelKey(q)))
        ans.push_back(dict[vowelKey(q)]);
      else
        ans.push_back("");

    return ans;
  }

 private:
  string lowerKey(const string& word) {
    string s{"$"};
    for (char c : word)
      s += tolower(c);
    return s;
  }

  string vowelKey(const string& word) {
    string s;
    for (char c : word)
      s += string("aeiou").find(tolower(c)) != string::npos ? '*' : tolower(c);
    return s;
  }
};
			

class Solution {
  public String[] spellchecker(String[] wordlist, String[] queries) {
    List<String> ans = new ArrayList<>();
    Map<String, String> dict = new HashMap<>();

    for (final String word : wordlist) {
      dict.putIfAbsent(word, word);
      dict.putIfAbsent(lowerKey(word), word);
      dict.putIfAbsent(vowelKey(word), word);
    }

    for (final String q : queries)
      if (dict.containsKey(q))
        ans.add(dict.get(q));
      else if (dict.containsKey(lowerKey(q)))
        ans.add(dict.get(lowerKey(q)));
      else if (dict.containsKey(vowelKey(q)))
        ans.add(dict.get(vowelKey(q)));
      else
        ans.add("");

    return ans.toArray(new String[0]);
  }

  private String lowerKey(final String word) {
    return "$" + word.toLowerCase();
  }

  private String vowelKey(final String word) {
    String s = "";
    for (char c : word.toCharArray())
      s += isVowel(c) ? '*' : Character.toLowerCase(c);
    return s;
  }

  private boolean isVowel(char c) {
    c = Character.toLowerCase(c);
    return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
  }
}
			

class Solution:
  def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:
    def lowerKey(word: str) -> str:
      return '$' + ''.join([c.lower() for c in word])

    def vowelKey(word: str) -> str:
      return ''.join(['*' if c.lower() in 'aeiou' else c.lower() for c in word])

    ans = []
    dict = {}

    for word in wordlist:
      dict.setdefault(word, word)
      dict.setdefault(lowerKey(word), word)
      dict.setdefault(vowelKey(word), word)

    for q in queries:
      if q in dict:
        ans.append(dict[q])
      elif lowerKey(q) in dict:
        ans.append(dict[lowerKey(q)])
      elif vowelKey(q) in dict:
        ans.append(dict[vowelKey(q)])
      else:
        ans.append('')

    return ans