문제

 

Most Common Word - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문자열에서 금지된 단어 (banned)를 제외한 단어들 중 가장 빈도수가 높은것을 출력하는 문제이다.

 

입출력

#Case 1
Input: s = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"

#Case 2
Input: s = "a.", banned = []
Output: "a"

#Case 3
Input: s = "Bob", banned = []
Output: "bob"

 

풀이

class Solution:
    def mostCommonWord(self, s: str, banned: List[str]) -> str:
        
        word = []       
        dic = collections.defaultdict(int)
        s = s.lower()
        
        for x in s : 
            if x.isalpha() == True:
                word.append(x)
            
            else:
                w = "".join(word) #list > str
                if w not in banned and w != '': 
                    dic[w]+=1
                word=[]
        
        #for문에서 else문 안 탄 경우 딕셔너리 추가 
        w = "".join(word)  
        if w not in banned and w != '': 
            dic[w]+=1
                    
        res = collections.Counter(dic)
        
        #Couter 객체의 가장 빈도수가 높은 key값(단어) return
        return res.most_common(1)[0][0]

 

희히

반응형

+ Recent posts