966: Vowel-Spellchecker
Medium
table of contents
This question is just an implementation question. The main gist of this question is you have to check in this exact order if:
- check if the exact
querystring is present in thewordList- return it
- check if the case-insensitive
querystring is present in thewordList- return the first instance of it
- check if the vowel-error
querystring is present in thewordList- return the first instance of it
- else, return an empty string
Then, you can simply create iterate through wordlist and
create an unordered_set/unordered_map to check
for the first three cases:
unordered_set<string> wordSet;
unordered_map<string, string> caseMatch;
unordered_map<string, string> vowelMatch;
string lowerCase, noVowels;
for (string& word : wordlist) {
wordSet.insert(word);
lowerCase = toLowerCase(word);
// only create mapping if `lowerCase` doesn't exist
if (!caseMatch.count(lowerCase)) {
caseMatch[lowerCase] = word;
}
noVowels = removeVowels(lowerCase);
// only create mapping if `noVowels` doesn't exist
if (!vowelMatch.count(noVowels)) {
vowelMatch[noVowels] = word;
}
}Finally, you can simply run through the four steps, using the
unordered_set/unordered_map to check if any of
the conditions are fulfilled for each query:
vector<string> ans;
for (string& query : queries) {
if (wordSet.count(query)) {
ans.push_back(query);
} else {
lowerCase = toLowerCase(query);
noVowels = removeVowels(lowerCase);
if (caseMatch.count(lowerCase)) {
ans.push_back(caseMatch[lowerCase]);
} else if (vowelMatch.count(noVowels)) {
ans.push_back(vowelMatch[noVowels]);
} else {
ans.push_back("");
}
}
}
return ans;code
class Solution {
public:
vector<string> spellchecker(vector<string>& wordlist, vector<string>& queries) {
unordered_set<string> wordSet;
unordered_map<string, string> caseMatch;
unordered_map<string, string> vowelMatch;
string lowerCase, noVowels;
for (string& word : wordlist) {
wordSet.insert(word);
lowerCase = toLowerCase(word);
if (!caseMatch.count(lowerCase)) {
caseMatch[lowerCase] = word;
}
noVowels = removeVowels(lowerCase);
if (!vowelMatch.count(noVowels)) {
vowelMatch[noVowels] = word;
}
}
vector<string> ans;
for (string& query : queries) {
if (wordSet.count(query)) {
ans.push_back(query);
} else {
lowerCase = toLowerCase(query);
noVowels = removeVowels(lowerCase);
if (caseMatch.count(lowerCase)) {
ans.push_back(caseMatch[lowerCase]);
} else if (vowelMatch.count(noVowels)) {
ans.push_back(vowelMatch[noVowels]);
} else {
ans.push_back("");
}
}
}
return ans;
}
private:
string toLowerCase (string word) {
for (char& c : word) {
c = tolower(c);
}
return word;
}
string removeVowels (string word) {
string noVowels = "";
for (char& c : word) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
noVowels += "*";
} else {
noVowels += c;
}
}
return noVowels;
}
};