-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path819_mostcommonwords.cpp
79 lines (61 loc) · 1.55 KB
/
819_mostcommonwords.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
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
using namespace std;
string ToLower(char * a)
{
string strLower(a,strlen(a));
for(int i=0; i<strlen(a); i++)
{
strLower[i] = tolower(a[i]);
}
return strLower;
}
class Solution
{
public:
string mostCommonWord(string paragraph, vector<string>& banned)
{
//tokenize paragraph, check word is in banned set or not, if not
//then add to map of occurrences, keep track of most frequent word
//
//
unordered_set<string> setBanned(banned.begin(), banned.end());
unordered_map<string,int> mapFreq;
char * copy = new char[paragraph.length()+1];
strncpy(copy,paragraph.c_str(),paragraph.length());
copy[paragraph.length()]='\0';
string mostCommonWord = "";
int nMaxFreq = 0;
char * curTok = strtok(copy, "!?',;. " );
while (curTok != NULL)
{
//if tolower of cur token is not in banned set increment frequency
string strLowWord = ToLower(curTok);
if(setBanned.find(strLowWord) == setBanned.end())
{
//not found in banned set , increment frequency
//try to find in map
mapFreq[strLowWord]++;
int freq = mapFreq[strLowWord];
if (freq>nMaxFreq)
{
mostCommonWord= strLowWord;
nMaxFreq = freq;
}
}
//find next
curTok = strtok(NULL, "!?',;. ");
}
return mostCommonWord;
}
};
int main()
{
Solution S1;
return 0;
}