1454. Word Frequency Count
class Solution {
public:
/**
* @param s: The string s
* @param excludeList: The excludeList
* @return: Return the most frequent words
*/
vector<string> getWords(string &s, vector<string> &excludeList) {
// Write your code here
vector<string> res;
const int size = s.size();
if(size == 0){
return res;
}
map<string, int> cnt;
unordered_set<string> exSet;
for(auto i : excludeList){
exSet.insert(i);
}
int i = 0;
while(i < size){
while(i < size && !(s[i] >= 'A' && s[i] <= 'z')){
i++;
}
if(i == size){
break;
}
int start = i;
while(i < size && s[i] >= 'A' && s[i] <= 'z'){
i++;
}
string word = s.substr(start, i - start);
string lowW = toLow(word);
if(exSet.find(lowW) == exSet.end()){
cnt[lowW]++;
}
}
int maxFreq = 0;
for(auto i : cnt){
maxFreq = max(maxFreq, i.second);
}
for(auto i : cnt){
if(i.second == maxFreq){
res.push_back(i.first);
}
}
return res;
}
string toLow(string &s){
for(int i = 0; i < s.size(); i++){
if(s[i] >= 'A' && s[i] <= 'Z'){
s[i] = (char)'a' + s[i] - 'A';
}
}
return s;
}
};
Comments
Post a Comment