leetcode/0966.Vowel-Spellchecker/README.md
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:
wordlist = ["yellow"], query = "YellOw": correct = "yellow"wordlist = ["Yellow"], query = "yellow": correct = "Yellow"wordlist = ["yellow"], query = "yellow": correct = "yellow"wordlist = ["YellOw"], query = "yollow": correct = "YellOw"wordlist = ["YellOw"], query = "yeellow": correct = "" (no match)wordlist = ["YellOw"], query = "yllw": correct = "" (no match)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"]
Note:
1 <= wordlist.length <= 50001 <= queries.length <= 50001 <= wordlist[i].length <= 71 <= queries[i].length <= 7wordlist and queries consist only of english letters.在给定单词列表 wordlist 的情况下,我们希望实现一个拼写检查器,将查询单词转换为正确的单词。
对于给定的查询单词 query,拼写检查器将会处理两类拼写错误:
此外,拼写检查器还按照以下优先级规则操作:
给出一些查询 queries,返回一个单词列表 answer,其中 answer[i] 是由查询 query = queries[i] 得到的正确单词。
map 来解题。依题意分为 3 种情况,查询字符串完全匹配;查询字符串只是大小写不同;查询字符串有元音错误。第一种情况用 map key 直接匹配即可。第二种情况,利用 map 将单词从小写形式转换成原单词正确的大小写形式。第三种情况,利用 map 将单词从忽略元音的小写形式换成原单词正确形式。最后注意一下题目最后给的 4 个优先级规则即可。package leetcode
import "strings"
func spellchecker(wordlist []string, queries []string) []string {
wordsPerfect, wordsCap, wordsVowel := map[string]bool{}, map[string]string{}, map[string]string{}
for _, word := range wordlist {
wordsPerfect[word] = true
wordLow := strings.ToLower(word)
if _, ok := wordsCap[wordLow]; !ok {
wordsCap[wordLow] = word
}
wordLowVowel := devowel(wordLow)
if _, ok := wordsVowel[wordLowVowel]; !ok {
wordsVowel[wordLowVowel] = word
}
}
res, index := make([]string, len(queries)), 0
for _, query := range queries {
if _, ok := wordsPerfect[query]; ok {
res[index] = query
index++
continue
}
queryL := strings.ToLower(query)
if v, ok := wordsCap[queryL]; ok {
res[index] = v
index++
continue
}
queryLV := devowel(queryL)
if v, ok := wordsVowel[queryLV]; ok {
res[index] = v
index++
continue
}
res[index] = ""
index++
}
return res
}
func devowel(word string) string {
runes := []rune(word)
for k, c := range runes {
if c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' {
runes[k] = '*'
}
}
return string(runes)
}