-
Notifications
You must be signed in to change notification settings - Fork 0
/
Most-common-word.cpp
55 lines (52 loc) · 1.48 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
class Solution {
public:
bool isBanned(vector<string>& banned, string word)
{
for(int i = 0; i< banned.size(); i++)
{
if(banned[i] == word)
return true;
}
return false;
}
string mostCommonWord(string paragraph, vector<string>& banned) {
int len = paragraph.size();
for(int i =0; i < len ; i++)
{
if(isupper(paragraph[i]))
paragraph[i] = tolower(paragraph[i]);
}
string word;
unordered_map<string, int>mp;
for(int i =0; i< len; i++)
{
word ="";
while(i < len && paragraph[i] >= 'a' && paragraph[i] <= 'z')
{
word += paragraph[i];
i+=1;
}
if(word != "" && word != " ")
{
mp[word]++;
}
}
//cout <<mp.size()<<endl;
string result = "";
int smallest = INT_MIN;
for(auto x : mp)
{
// If frequency is > than my highest current frequency, store frequency and check if word is banned
if(x.second >= smallest)
{
// if word is NOT banned, store its frequency and word
if(!isBanned(banned, x.first))
{
result = x.first;
smallest = x.second;
}
}
}
return result;
}
};