LeetCode 코딩 문제 2020/11/21 - Most Common Word

이호현·2020년 11월 20일
0

Algorithm

목록 보기
18/138

[문제]

Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.

Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.

요약
문자열중에 특수기호 제외한 단어중 가장 많이 반복되는 단어를 찾아라.
banned는 제외할 단어.

[풀이]

var mostCommonWord = function(paragraph, banned) {
  const sChar = /[\{\}\[\]\/?.,;:|\)*~`!^\-_+<>@\#$%&\\\=\(\'\"]/gi

  while(sChar.test(paragraph) || paragraph.includes('  ')) {
    paragraph = paragraph.replace(sChar, ' ').replace('  ', ' ');
  }

  const splitArr = paragraph.split(' ').map(str => str.toLowerCase()).filter(str => !banned.includes(str));
  const res = splitArr.reduce((obj, str) => {
    obj[str] ? obj[str] += 1 : obj[str] = 1
    return obj;
  }, {});
  const valuesArr = Object.values(res);
  const maxIdx = valuesArr.indexOf(Math.max(...valuesArr));
  return Object.keys(res)[maxIdx];
};

특수문자 정규식을 만들고, 문자열에서 특수문자를 ' '로 변환.
' '가 두칸인 경우 한칸으로 만들고 공백을 기준으로 split한 후 소문자 변환하고 banned에 포함된 단어들은 제거.
각 단어가 몇 번씩 들어가는지 세고, 그중 가장 많이 들어간 단어를 찾음.
가장 많이 반복된 단어 찾는 방법이 더 간단한게 있을거 같은 느낌인데... 흠...

제일 빠른 사람거 코드 봤는데... 쩝...
/\W/로 특문 제거 하려는데 ' '때문에 안되서 고민하다가 저렇게 했는데
/\W+/이렇게 하는 방법이 있었네...
아직도 배워야 할게 많네요...

profile
평생 개발자로 살고싶습니다

0개의 댓글