1.문제
Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.
The words in paragraph are case-insensitive and the answer should be returned in lowercase.
금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하는 문제이다. 대소문자 구분을 하지 않으며, 구두점(마침표 쉼표 등) 또한 무시한다.
Example 1
Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.
Example 2
Input: paragraph = "a.", banned = []
Output: "a"
Constraints:
- 1 <= paragraph.length <= 1000
- paragraph consists of English letters, space ' ', or one of the symbols: "!?',;.".
- 0 <= banned.length <= 100
- 1 <= banned[i].length <= 10
- banned[i] consists of only lowercase English letters.
2.풀이
- 대소문자를 구분하지 않으므로 모두 소문자로 바꿔주고 구두점을 제거해준다.
- 반복문을 돌면서 금지단어라면 삭제해준다.
- 삭제되지 않은 단어들의 갯수를 체크해서 map에 넣어준다.
- 갯수가 가장 많은 단어를 리턴한다.
/**
* @param {string} paragraph
* @param {string[]} banned
* @return {string}
*/
const mostCommonWord = function (paragraph, banned) {
let map = {};
let count = 0;
paragraph = paragraph.toLowerCase().replace(/[.,?!;\']/g, " "); //punctuation 제거
paragraph = paragraph.split(" ");
banned.forEach((word) => {
for (let i = 0; i < paragraph.length; i++) {
if (paragraph[i] === word) {
// banned 의 단어와 같은 단어면 배열에서 삭제해줌
paragraph.splice(i, 1);
i--;
}
}
});
for (let i = 0; i < paragraph.length; i++) {
// 남아있는 단어들의 갯수를 체크해서 map에 저장
if (paragraph[i] !== "") {
map[paragraph[i]]
? (map[paragraph[i]] = map[paragraph[i]] + 1)
: (map[paragraph[i]] = 1);
}
}
for (let key in map) {
// 갯수가 가장 많은 단어의 갯수를 저장
count = Math.max(map[key], count);
}
const getKeyByValue = (object, value) => {
// value 로 key 값 찾기
return Object.keys(object).find((key) => object[key] === value);
};
return getKeyByValue(map, count);
};
3.결과
