Skip to content

Commit 9c59d86

Browse files
committedJan 15, 2020
Add solution #819
1 parent bb77f22 commit 9c59d86

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
 

‎solutions/0819-most-common-word.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* 819. Most Common Word
3+
* https://leetcode.com/problems/most-common-word/
4+
* Difficulty: Easy
5+
*
6+
* Given a paragraph and a list of banned words, return the most frequent word that
7+
* is not in the list of banned words. It is guaranteed there is at least one word
8+
* that isn't banned, and that the answer is unique.
9+
*
10+
* Words in the list of banned words are given in lowercase, and free of punctuation.
11+
* Words in the paragraph are not case sensitive. The answer is in lowercase.
12+
*/
13+
14+
/**
15+
* @param {string} paragraph
16+
* @param {string[]} banned
17+
* @return {string}
18+
*/
19+
var mostCommonWord = function(paragraph, banned) {
20+
const occurrences = new Map();
21+
paragraph.toLowerCase().replace(/[^\w\s]/g, ' ').split(/\s+/).forEach(word => {
22+
if (!banned.includes(word)) {
23+
occurrences.set(word, occurrences.has(word) ? occurrences.get(word) + 1 : 1);
24+
}
25+
});
26+
return Array.from(occurrences).sort((a, b) => b[1] - a[1])[0][0];
27+
};

0 commit comments

Comments
 (0)
Please sign in to comment.