-
Notifications
You must be signed in to change notification settings - Fork 0
/
most-common-word.cpp
67 lines (61 loc) · 1.82 KB
/
most-common-word.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Solution {
public:
bool check(char c){
if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')){
return true;
}
return false;
}
void toLowCase(string& str){
for(string::iterator it = str.begin(), end = str.end(); it != end; it ++){
if( (*it) >= 'A' && (*it) <= 'Z'){
*it += 32;
}
}
}
string mostCommonWord(string paragraph, vector<string>& banned) {
map<string, int> Count;
string::iterator start = paragraph.begin();
bool word = true;
for(string::iterator it = paragraph.begin(), end = paragraph.end(); it != end; it ++){
if(!check(*it)){
if(word){
string str = string(start,it);
toLowCase(str);
Count[str] ++;
word = false;
}
}
else{
if(!word){
start = it;
}
word = true;
}
}
if(word){
string str = string(start,paragraph.end());
toLowCase(str);
Count[str] ++;
word = false;
}
int maxx = -1;
string ans = "";
for(auto it = Count.begin(), end = Count.end(); it != end; it ++){
if((*it).second > maxx){
bool flag = false;
for(int j = 0 ; j < banned.size() ; j++){
if((*it).first == banned[j]){
flag = true;
break;
}
}
if(!flag){
maxx = (*it).second;
ans = (*it).first;
}
}
}
return ans;
}
};