[LeetCode] 819. Most Common Word (가장 흔한 단어)

🔗 문제

링크 : https://leetcode.com/problems/most-common-word/

 

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

  • 금지된 단어 제외한 가장 흔하게 등장하는 단어를 출력.
  • 대소문자 구분하지 않는다.
  • 구두점(마침표,쉼표 등) 는 무시

📝 포인트

  • 정규식 사용법
  • collections.Counter() 사용법
replaceAll("\\p{Punct}", " ") // 구두점 제거




List<String> keySetList = new ArrayList<>(keyMap.keySet());

//key의 value값으로 내림차순 정렬
//keySetList에 value값이 큰 순서대로 key가 들어간다
Collections.sort(keySetList, (o1, o2) -> (keyMap.get(o2).compareTo(keyMap.get(o1))));


keyMap = {the=1, a=1, ball=2, bob=1, far=1, flew=1, was=1, after=1, it=1}
keySetList = [ball, the, a, bob, far, flew, was, after, it]

 

💻 코드 (python)

  • 정규식 사용 : re.sub 
import collections
import re
from typing import List

class solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        # \n :단어문자 , ^ : not
        words = [word for word in re.sub(r'[^\w]', ' ', paragraph).lower().split()
                 if word not in banned]

        counts = collections.Counter(words)
        print(counts)
        return counts.most_common(1)[0][0]



paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]

ss = solution()
rr = ss.mostCommonWord(paragraph, banned)
print(rr)

💻 코드 (java)

package org.kyhslam.leetCode;

import java.util.*;

public class leet_819 {


    public String mostCommonWord(String paragraph, String[] banned) {

        String answer = "";

        //금지된 단어 저장
        HashSet banSet = new HashSet();
        for (int i = 0; i < banned.length; i++) {
            banSet.add(banned[i]);
        }

        Map<String, Integer> keyMap = new HashMap<>(); // 문자 , count

        String[] a = paragraph.toLowerCase().replaceAll("\\p{Punct}", " ").split(" ");
        for (int i = 0; i < a.length; i++) {
            String ee = a[i];
            System.out.println("ee = " + ee);
        }
        System.out.println("Arrays.toString(a) = " + Arrays.toString(a));

        for (int i = 0; i < a.length; i++) {
            char[] temp = a[i].toCharArray();
            StringBuilder makedLetter = new StringBuilder(); // key 만들 문자
            for (char c : temp) {
                if(Character.isLetter(c)){
                    makedLetter.append(c);
                }
            }

            if (!banSet.contains(makedLetter.toString()) && !"".equals(makedLetter.toString())) {
                if(keyMap.containsKey(makedLetter.toString())){
                    keyMap.put(makedLetter.toString(), (keyMap.get(makedLetter.toString()) + 1));
                }else{
                    keyMap.put(makedLetter.toString(), 1);
                }
            }
        }

        System.out.println("keyMap = " + keyMap);

        List<String> keySetList = new ArrayList<>(keyMap.keySet());
        Collections.sort(keySetList, (o1, o2) -> (keyMap.get(o2).compareTo(keyMap.get(o1))));

        System.out.println("keySetList = " + keySetList);

        //keySetList.get(0);
        return keySetList.get(0);
    }


    public static void main(String[] args) {

        leet_819 t = new leet_819();

        //String paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.";
        //String[] banned = {"hit"};
        String paragraph = "a, a, a, a, b,b,b,c, c";
        String[] banned = {"a"}; //{"hit"};



        String a = t.mostCommonWord(paragraph, banned);
        System.out.println("a = " + a);
    }
}

댓글

Designed by JB FACTORY