문제 링크 : Most Common Word
/**
* @param {string} paragraph
* @param {string[]} banned
* @return {string}
*/
var mostCommonWord = function(paragraph, banned) {
const reg = /[\{\}\[\]\/?.,;:|\)*~`!^\-_+<>@\#$%&\\\=\(\'\"]/gi;
let resultMap = new Map();
paragraph.split(' ').forEach(e => {
const word = e.toLowerCase().replace(reg, '')
if(!banned.includes(word)) {
resultMap.get(word) ? resultMap.set(word, resultMap.get(word)+1) : resultMap.set(word, 1)
}
})
return [...resultMap.entries()].reduce((a,b) => a[1] > b[1] ? a : b)[0]
};
반례
paragraph = "a, a, a, a, b,b,b,c, c"
banned = ["a"]
/**
* @param {string} paragraph
* @param {string[]} banned
* @return {string}
*/
var mostCommonWord = function(paragraph, banned) {
let arr = paragraph.toLowerCase().split(/\W+/g)
let map = {}
for(let word of arr) {
if(!map[word]) {
map[word] = 1
} else {
map[word]++
}
}
return Object.keys(map).sort((a,b) => {
return map[b] - map[a]
}).filter(word => !banned.includes(word) && word !== '')[0]
};
\W
- Matches any character that is not a word character (alphanumeric & underscore).
Equivalent to [^A-Za-z0-9_]
+
- Matches 1 or more of the preceding token.
즉. 특수문자이거나 특수문자를 포함하는 공백들로 split하게 됨