본문 바로가기
코딩테스트(알고리즘)/leetCode

[leetCode] 819. Most Common Word (Javascript,Python)

by Cafe Mocha 2023. 3. 26.

Most Common Word - LeetCode

 

Most Common Word - LeetCode

Can you solve this real interview question? Most Common Word - 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 tha

leetcode.com


알고리즘: 구현,정렬,정규식

 

새롭게 알게 된 방법

  • Javasript
    • Object.entries -> 객체를 key,value 배열로 바꿔준다.
  • Python
    • string.punctuation : 특수문자 모음
    • collections.Counter : 배열을 넣으면 배열의 수를 계산해준다.

- Javascript

function solution() {
  let input = require("fs")
    .readFileSync("input.txt") //"/dev/stdin"
    .toString()
    .split("\n")
    .map((val) => val.trim());
  let paragraph = input.shift();
  let banned = [input.shift()];
  let pattern = /[^\w\s]/gi;
  paragraph = paragraph
    .replace(pattern, " ")
    .toLowerCase()
    .split(" ")
    .filter((v) => v !== "");

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

  let counts = {};

  for (let i = 0; i < paragraph.length; i++) {
    if (counts[paragraph[i]]) {
      counts[paragraph[i]]++;
    } else {
      counts[paragraph[i]] = 1;
    }
  }

  counts = Object.entries(counts).sort((a, b) => b[1] - a[1]);

  console.log(counts[0][0]);
}

solution();

- Python

import sys
from string import punctuation
from collections import Counter

sys.stdin = open("leetCode/819/input.txt","r")
input = sys.stdin.readline

paragraph = input()
banned = list(input().split())
for character in punctuation:
    paragraph = paragraph.replace(character," ")
paragraph = list(paragraph.lower().split())

counts = Counter(paragraph)

for word in banned:
    del counts[word]

print(max(counts, key=counts.get))