题目
分析
题意简单说来就是:
- 模糊匹配大小写
- 模糊匹配大小写的基础上,模糊匹配元音
解法:
- 模糊匹配大小写,那么我们就全转换成大写/小写来用hash表存
- 模糊匹配元音,先在全部是大写/小写的基础上,把语音字母用其他符号来表示,我这里使用数字“1”
代码
class Solution {
private:
string get_upper(const string& str) {
string res;
for (auto & c : str) {
if (c >= 'a' && c <= 'z') {
res += c - 'a' + 'A';
} else {
res += c;
}
}
return res;
}
string get_vowel(const string& str) {
string res;
for (auto & c : str) {
if (is_vowel(c)) {
res += '1';
} else {
res += c;
}
}
return res;
}
bool is_vowel(const char& c) {
if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
return true;
}
return false;
}
public:
vector<string> spellchecker(vector<string>& wordlist, vector<string>& queries) {
unordered_set<string> st(wordlist.begin(), wordlist.end());
unordered_map<string, string> mp1;
unordered_map<string, string> mp2;
for (auto & word : wordlist) {
string up_s = get_upper(word);
string vo_s = get_vowel(up_s);
if (!mp1.count(up_s)) {
mp1[up_s] = word;
}
if (!mp2.count(vo_s)) {
mp2[vo_s] = word;
}
}
vector<string> res;
for (auto & word : queries) {
string up_s = get_upper(word);
string vo_s = get_vowel(up_s);
if (st.count(word)) {
res.push_back(word);
} else if (mp1.count(up_s)) {
res.push_back(mp1[up_s]);
} else if (mp2.count(vo_s)) {
res.push_back(mp2[vo_s]);
} else {
res.push_back("");
}
}
return res;
}
};
网友评论