解題思路:
(1)首先遍歷字符串,取每一個單詞,並將其轉化爲小寫字母
(2)判斷是否在停用詞中,不在將其作爲map的key,value表示該單詞出現的次數
(3)邊遍歷,邊記錄出現次數最多的單詞,注意根據題目要求,只有一個最大值
class Solution {
public:
string mostCommonWord(string s, vector<string>& banned) {
int i=0,max=0;
int start=0,end=0;
string temp,str;
unordered_map<string,int> mp;
while(i<s.length()) {
if(isalpha(s[i])) {
start = i;
while(i<s.length()&&isalpha(s[i])) {
s[i] = tolower(s[i]);
i++;
}
end = i;
temp = s.substr(start,end-start);
if(find(banned.begin(),banned.end(),temp)==banned.end()) {
mp[temp]++;
if(mp[temp]>max) {
str = temp;
max = mp[temp];
}
}
} else i++;
}
return str;
}
};