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))
'코딩테스트(알고리즘) > leetCode' 카테고리의 다른 글
[leetCode] 3. Longest Substring Without Repeating Characters (Javascript) (0) | 2022.06.26 |
---|---|
[leetCode] 125. Valid Palindrome (Javascript) (0) | 2022.06.25 |
[leetCode] 11. Container With Most Water (Javascript) (0) | 2022.06.25 |
[leetCode] 1. Two Sum (Javascript) (0) | 2022.06.25 |
[leetCode] 13.Roman to Integer (Javascript) (0) | 2022.06.24 |