作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/vowel-spellchecker/description/
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:
Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist.
Vowel Errors: If after replacing the vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist.
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:
现在给了一个单词字典,给出了一堆要查询的词,要返回查询结果。查询的功能如下:
这个题还是挺烦的,并不是一个考察搜索的题目,可以直接使用字典去解决。
首先,判断有没有相同的单词,这个很好办,直接使用set;
其次,要判断改变某些大小写,这里注意的是可以把要查询的字符串中的任意字符转换成大小写,如果抽象一点的话就是,忽略字符串所有字符的大小写之后匹配即可。因为要返回第一个出现的,所以,我们把要字典字符串反过来构成字典,这样就保存了忽略大小写之后的字符串第一个出现的位置。
最后,要把元音字符进行忽略,可以任意转换。这个思路很邪,直接把元音字符转成同样的字符,这样只要把元音统一替换之后的结果相等即可。同样反向构成字典。
python代码如下:
class Solution(object):
def spellchecker(self, wordlist, queries):
"""
:type wordlist: List[str]
:type queries: List[str]
:rtype: List[str]
"""
wordset = set(wordlist)
capdict = {word.lower() : word for word in wordlist[::-1]}
vodict = {re.sub(r'[aeiou]', '#', word.lower()) : word for word in wordlist[::-1]}
res = []
for q in queries:
if q in wordset:
res.append(q)
elif q.lower() in capdict:
res.append(capdict[q.lower()])
elif re.sub(r'[aeiou]', '#', q.lower()) in vodict:
res.append(vodict[re.sub(r'[aeiou]', '#', q.lower())])
else:
res.append("")
return res
2018 年 12 月 30 日 —— 周赛差强人意
手机扫一扫
移动阅读更方便
你可能感兴趣的文章