LeetCode-in-Java

966. Vowel Spellchecker

Medium

Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.

For a given query word, the spell checker handles two categories of spelling mistakes:

In addition, the spell checker operates under the following precedence rules:

Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].

Example 1:

Input: wordlist = [“KiTe”,”kite”,”hare”,”Hare”], queries = [“kite”,”Kite”,”KiTe”,”Hare”,”HARE”,”Hear”,”hear”,”keti”,”keet”,”keto”]

Output: [“kite”,”KiTe”,”KiTe”,”Hare”,”hare”,””,””,”KiTe”,””,”KiTe”]

Example 2:

Input: wordlist = [“yellow”], queries = [“YellOw”]

Output: [“yellow”]

Constraints:

Solution

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Solution {
    private Set<String> matched;
    private Map<String, String> capitalizations;
    private Map<String, String> vowelErrors;

    private boolean isVowel(char w) {
        return w == 'a' || w == 'e' || w == 'i' || w == 'o' || w == 'u';
    }

    private String removeVowels(String word) {
        StringBuilder s = new StringBuilder();
        for (char w : word.toCharArray()) {
            s.append(isVowel(w) ? '*' : w);
        }
        return s.toString();
    }

    private String solveQuery(String query) {
        if (matched.contains(query)) {
            return query;
        }
        String word = query.toLowerCase();
        if (capitalizations.containsKey(word)) {
            return capitalizations.get(word);
        }
        word = removeVowels(word);
        if (vowelErrors.containsKey(word)) {
            return vowelErrors.get(word);
        }
        return "";
    }

    public String[] spellchecker(String[] wordlist, String[] queries) {
        String[] answer = new String[queries.length];
        matched = new HashSet<>();
        capitalizations = new HashMap<>();
        vowelErrors = new HashMap<>();
        for (String word : wordlist) {
            matched.add(word);
            String s = word.toLowerCase();
            capitalizations.putIfAbsent(s, word);
            s = removeVowels(s);
            vowelErrors.putIfAbsent(s, word);
        }
        for (int i = 0; i < queries.length; i++) {
            answer[i] = solveQuery(queries[i]);
        }
        return answer;
    }
}