819. Most Common Word

동청·2022년 9월 21일
0

leetcode

목록 보기
21/39

Problem

leetcode 바로가기

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.

Solution

/**
 * @param {string} paragraph
 * @param {string[]} banned
 * @return {string}
 */
 var mostCommonWord = function(paragraph, banned) {
  let arr = paragraph.toLowerCase().split(/[^A-Za-z]/g);

  for (let i = 0; i < arr.length; i++) {
  arr = arr.filter((word) => word != banned[i]);
} 
  let obj = {};

  for (let i = 0; i < arr.length; i++) {
    obj[arr[i]] ? obj[arr[i]] += 1 : obj[arr[i]] = 1;
  }

  const sortable = Object.entries(obj).sort(([, a], [, b]) => b - a).reduce((r, [k, v]) => ({ ...r, [k]: v }), {});

  let result = Object.keys(sortable);

  if (result[0] == "") {
    return result[1];
  } else {
    return result[0]
  }
};

0개의 댓글