LeetCode 819. Most Common Word (Java)

Kim Yongbin·2024년 4월 13일
post-thumbnail

문제

https://leetcode.com/problems/most-common-word/description/

Code

1차

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        Map<String, Integer> wordCountMap = new HashMap<>();

        for (String p : paragraph.split(" ")) {
            String word = p.toLowerCase().replaceAll("[^a-zA-Z]", "");

            if (!Arrays.asList(banned).contains(word)) {
                int count = wordCountMap.getOrDefault(word, 0);
                wordCountMap.put(word.toLowerCase(), count + 1);
            }
        }

        return Collections.max(wordCountMap.entrySet(), Map.Entry.comparingByValue()).getKey();
    }
}

최종

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        Map<String, Integer> wordCountMap = new HashMap<>();

        for (String word : paragraph.toLowerCase().replaceAll("[^a-zA-Z]+", " ").split(" ")) {
            if (!Arrays.asList(banned).contains(word)) {
                int count = wordCountMap.getOrDefault(word, 0);
                wordCountMap.put(word.toLowerCase(), count + 1);
            }
        }

        return Collections.max(wordCountMap.entrySet(), Map.Entry.comparingByValue()).getKey();
    }
}

  1. Collections.max(wordCountMap.entrySet(), Map.Entry.comparingByValue()).getKey();
    1. Java Collections max 함수에 Comparator를 추가로 넣어줌으로써 정렬하는 기준을 특정할 수 있다.
  2. replaceAll("[^a-zA-Z]+", " ")
    1. ^[a-zA-Z]는 알파벳이 아닌 글자를 한 글자 단위로 매칭시킨다.
      1. 즉, a, b‘a’, ',’ , ‘ ’, ‘b’ 를 하나씩 매칭 시킨다.

        a b (중간 공백 2칸)

    2. ^[a-zA-Z]+는 알파벳이 아닌 여러 글자를 한 번에 매칭 시킬 수 있다.
      1. a, b‘a’, ', ‘, ‘b’

        a b (중간 공백 1칸)

profile
반박 시 여러분의 말이 맞습니다.

0개의 댓글