[Work@] Restaurant Reviews

Restaurant Reviews

A restaurant listing website has asked you to analyse the reviews on its restaurants.
The reviews need to be sorted by how good they are, the best reviews go on top. The goodness a review is determined by the number of times “good words” appear in them. You are given a list of good words.

Given n reviews and m good words, sort the reviews, such that the one with most good words appears first. For reviews with the same number of good words, maintain the initial order.

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
string parse(string& s, int& i) {
int n = s.length();
string res = "";
while(i < n and s[i] != ' ') {
res.push_back(s[i++]);
}
i++;
return res;
}

int countGoodWords(string& s, unordered_set<string>& us) {
int res = 0, i = 0, n = s.length();
while(i < n) {
auto token = parse(s,i);
res += us.count(token);
}
return res;
}

vector<string> orderReviews(vector<string> &reviews, vector<string> &goodWords) {
unordered_set<string> us(begin(goodWords), end(goodWords));
vector<pair<int, int>> order;
for(int i = 0; i < reviews.size(); i++) {
int count = countGoodWords(reviews[i], us);
order.push_back({count, i});
}
sort(begin(order), end(order), [](auto& a, auto& b) {
if(a.first == b.first) return a.second < b.second;
return a.first > b.first;
});

vector<string> res;
for(auto& [_, i] : order)
res.push_back(reviews[i]);
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/04/PS/WorkAt/restaurant-reviews/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.