|
| 1 | +/** |
| 2 | + * 966. Vowel Spellchecker |
| 3 | + * https://leetcode.com/problems/vowel-spellchecker/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word. |
| 7 | + * For a given query word, the spell checker handles two categories of spelling mistakes: |
| 8 | + * |
| 9 | + * - Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word |
| 10 | + * is returned with the same case as the case in the wordlist. |
| 11 | + * Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow" |
| 12 | + * Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow" |
| 13 | + * Example: wordlist = ["yellow"], query = "yellow": correct = "yellow" |
| 14 | + * - Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel |
| 15 | + * individually, it matches a word in the wordlist (case-insensitive), then the query word is returned |
| 16 | + * with the same case as the match in the wordlist. |
| 17 | + * Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw" |
| 18 | + * Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match) |
| 19 | + * Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match) |
| 20 | + * |
| 21 | + * In addition, the spell checker operates under the following precedence rules: |
| 22 | + * - When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back. |
| 23 | + * - When the query matches a word up to capitlization, you should return the first such match in the wordlist. |
| 24 | + * - When the query matches a word up to vowel errors, you should return the first such match in the wordlist. |
| 25 | + * - If the query has no matches in the wordlist, you should return the empty string. |
| 26 | + * |
| 27 | + * Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i]. |
| 28 | + */ |
| 29 | + |
| 30 | +/** |
| 31 | + * @param {string[]} words |
| 32 | + * @param {string[]} queries |
| 33 | + * @return {string[]} |
| 34 | + */ |
| 35 | +var spellchecker = function(words, queries) { |
| 36 | + const set = new Set(words); |
| 37 | + const map = new Map(); |
| 38 | + const format = s => s.toLowerCase().replace(/[aeiou]/g, '_'); |
| 39 | + words.forEach(word => { |
| 40 | + if (!map.has(word.toLowerCase())) map.set(word.toLowerCase(), word); |
| 41 | + if (!map.has(format(word))) map.set(format(word), word); |
| 42 | + }); |
| 43 | + return queries.map(q => set.has(q) ? q : map.get(q.toLowerCase()) || map.get(format(q)) || ''); |
| 44 | +}; |
0 commit comments