思路:
直接按照题意模拟即可,如果是cpp,就要用双指针算法,来实现字符串分割,如果是java,直接调用spilt即可
class Solution {
public:
unordered_map<string,int> mp;
unordered_map<string,int> ban;
bool check(char c){
return c>='a'&&c<='z'||c>='A'&&c<='Z';
}
string trans(string s){
for(auto &it:s){
if(it>='A'&&it<='Z') it=it-'A'+'a';
}
return s;
}
string mostCommonWord(string paragraph, vector<string>& banned) {
for(auto &it:banned) ban[it]++;
for(int i=0;i<paragraph.length();){
int j=i;
if(!check(paragraph[j])) {i++;continue;}
while(j<paragraph.length()&&check(paragraph[j])) j++;
mp[trans(paragraph.substr(i,j-i))]++;
i=j;
}
string ans;
int c=-1;
for(auto &[k,v]:mp){
if(!ban[k]&&v>c){
c=v;
ans=k;
}
}
return ans;
}
};
class Solution {
public String mostCommonWord(String paragraph, String[] banned) {
String[] res=paragraph.split("[^a-zA-Z]");
HashMap<String,Integer> map=new HashMap<>();
for (String re : res) {
if(re.equals("")) continue ;
re=re.toLowerCase();
map.put(re,map.getOrDefault(re,0)+1);
}
for (String s : banned) map.remove(s);
int count=-1;
String ans="";
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if(entry.getValue()>count){
count=entry.getValue();
ans=entry.getKey();
}
}
return ans;
}
}