[Leetcode] 819. most common word (python, javasciript)

728x90
반응형

1. python

from collections import defaultdict
import re

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        dict=defaultdict(int)
        paragraph=re.sub(r'[^\w]',' ',paragraph)
        # print(paragraph)
        for p in paragraph.lower().split():
            if p not in banned:
                dict[p]+=1
        return max(dict,key=dict.get)
        

cnt=collections.Counter(dict) 해서 return cnt.most_common(1)[0][0]으로 가져오는 방법도 있다

most_common(k): k개의 인자를 가져온다.

most_common(1)[0]: ('ball',2)

most_common(1)[0][0]: 'ball'

 

* 공부할 것 

정규 표현식, collections.Counter

 

2. javascript

 

/**
 * @param {string} paragraph
 * @param {string[]} banned
 * @return {string}
 */
var mostCommonWord = function(paragraph, banned) {
    dict={} 
    //띄어쓰기 외에 ,나 . 등을 ' '로 치환해서 배열로 만들어준다. 
    paragraph=paragraph.replace(/[^a-z]+/gi,' ').toLowerCase().split(' ');
	
    paragraph.forEach(p=>{
        if(p==='')return false; // forEach에서 continue대신 사용하는 방법 
        if(!dict[p]){
            dict[p]=1; //만약 객체에 없으면 초기값 지정
        }else{
            dict[p]+=1; //있으면 갯수 증가 
        }
    })
    banned.forEach(b=>{
        dict[b]=0 // banned에 있으면 갯수를 0으로 초기화 
    })
 // object에서 가장 최대값 가져오는 방법 
    let answer=Object.keys(dict).reduce((a,b)=>{
        return dict[a]>dict[b]?a:b;
    })
    return answer
};
728x90
반응형

'Leetcode' 카테고리의 다른 글

LeetCode - Array Partition 1  (0) 2020.10.06
LeetCode. Group Anagrams (python)  (0) 2020.10.06
22. Generate Parentheses  (0) 2020.10.03
680. Valid Palindrome II  (0) 2020.10.03
[LeetCode] 937. Reorder Data in Log Files (python, javascript)  (0) 2020.09.29
TAGS.

Comments