在给定单词列表?wordlist
?的情况下,我们希望实现一个拼写检查器,将查询单词转换为正确的单词。
对于给定的查询单词?query
,拼写检查器将会处理两类拼写错误:
wordlist = ["yellow"], query = "YellOw": correct = "yellow"
wordlist = ["Yellow"], query = "yellow": correct = "Yellow"
wordlist = ["yellow"], query = "yellow": correct = "yellow"
(‘a’、‘e’、‘i’、‘o’、‘u’)
分别替换为任何元音后,能与单词列表中的单词匹配(不区分大小写),则返回的正确单词与单词列表中的匹配项大小写相同。
wordlist = ["YellOw"], query = "yollow": correct = "YellOw"
wordlist = ["YellOw"], query = "yeellow": correct = ""
(无匹配项)wordlist = ["YellOw"], query = "yllw": correct = ""
(无匹配项)此外,拼写检查器还按照以下优先级规则操作:
queries
,返回一个单词列表 answer
,其中 answer[i]
是由查询 query = queries[i]
得到的正确单词。输入:wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"]
输出:["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"]
提示:
1 <= wordlist.length <= 5000
1 <= queries.length <= 5000
1 <= wordlist[i].length <= 7
1 <= queries[i].length <= 7
wordlist
和?queries
?中的所有字符串仅由英文字母组成。class Solution {
public:
string tolower(string& word){
string res = "";
for(char ch : word){
res += (ch <= 'Z' ? ch - 'A' + 'a' : ch);
}
return res;
}
string parse(string& word, vector<char>& mp){
string res = "";
for(char ch : word){
res += mp[ch];
}
return res;
}
vector<string> spellchecker(vector<string>& wordlist, vector<string>& queries) {
unordered_set<string> st(wordlist.begin(), wordlist.end());
unordered_map<string, vector<string>> mp1;
unordered_map<string, vector<string>> mp2;
vector<char> mp(128, '*');
for(char ch = 'A'; ch <= 'Z'; ch++){
char low = char(ch - 'A' + 'a');
mp[ch] = low;
mp[low] = low;
}
string aeiou = "AEIOUaeiou";
for(char ch : aeiou){
mp[ch] = '*';
}
for(string word : wordlist){
string low = tolower(word);
if(mp1.find(low) == mp1.end()){
mp1[low] = {word};
}else{
mp1[low].push_back(word);
}
string _word = parse(word, mp);
if(mp2.find(_word) == mp2.end()){
mp2[_word] = {word};
}else{
mp2[_word].push_back(word);
}
}
vector<string> res;
for(string q : queries){
if(st.find(q) != st.end()){
res.push_back(q);
}else{
string low = tolower(q);
if(mp1.find(low) != mp1.end()){
res.push_back(mp1[low].front());
}else{
string _word = parse(q, mp);
if(mp2.find(_word) != mp2.end()){
res.push_back(mp2[_word].front());
}else{
res.push_back("");
}
}
}
}
return res;
}
};
原文:https://www.cnblogs.com/zhanzq/p/11062921.html