[LeetCode] 819. Most Common Word

#819. Most Common Word

문제

주어진 문자열 paragraph에서 가장 많이 나온 단어를 반환하는 문제입니다. 단어는 대소문자를 구분하지 않으며 소문자로 리턴합니다.

설명

우선 paragraph는 대소문자를 구분하지 않지 때문에 str.toLowerCase() 를 이용해서 전부 소문자로 변경해줍니다.

그리고 str.replace() 를 통해 문자를 제외한 것들을 제거합니다. 문자만 남은 문자열에서 빈칸 ’ ‘을 기준으로 split()을 사용해서 자르고 단어의 배열로 만들어 줍니다. 이 단어의 배열을 돌면서 includes() 를 이용해서 banned에 포함되는 단어는 제외하하고, 단어를 키로, 나온 횟수를 값으로 가지는 data에 저장을하고, 이 data를 반복문으로 돌려 가장 많은 횟수를 가진 단어를 반환합니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
var mostCommonWord = function(paragraph, banned) {
  const data = {}; // 단어를 키로, 나온 횟수를 값으로 저장한다.

  // 입력 받은 paragraph에서 문자와 숫자를 제외하고 나머지를 제거한 후 소문자로 만든다.
  const str = paragraph.replace(/[^a-z]/gi," ").toLowerCase(); 
  const arr = str.split(' '); // ' '을 기준으로 배열로 만든다
  for (let s of arr) { // 이 배열을 돌면서
    if (s !== '' && !banned.includes(s)) { // 단어가 빈 값이 아니고, banned에 포함 안되는 경우에만.
      if (!data[s]) data[s] = 0; // 단어를 키로, 나온 횟수를 값으로 저장하는 data에 단어가 없으면 생성하고,
      data[s] += 1; // 횟수를 하나 증가 시킨다.
    }
  }
  let key = ''; // 가장 많이 나온 단어를 저장할 변수
  for (let i in data) {
    const count = data[i];
    if (!key) key = i; // 반복문을 처음 돌 때 첫 키값을 저장한다.
    if (count > data[key]) key = i; // key변수의 횟수보다 새로운 단어의 횟수가 많다면 key를 변경한다.
  }
  return key;
};

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:

1
2
3
4
5
6
7
8
9

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:

1
2
graph = "a.", banned = []
Output: "a"

Input: para

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.
Built with Hugo
Theme Stack designed by Jimmy