ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Java] leetcode 819. Most Common Word
    codingTest 2024. 10. 28. 19:50

     

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

    문제 분석

    금지된 단어를 제외하고 가장 자주 언급된 단어를 출력한다.

    (대소문자 구분X, 구두점은 무시한다.)

    입출력 예시

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

    사고의 흐름

    1. 금지 단어 replaceAll
    2. 공백으로 split
    3. Map에 넣기

    풀이

    개수를 세기 쉽도록 Map을 이용하였다.

    banned 배열은 금지하는 단어에 해당되는지 비교가능하도록 Set으로 만들어준다.

    public static String mostCommonWord(String paragraph, String[] banned) {
            Map<String, Integer> wordMap = new HashMap<>();
            Set<String> ban = new HashSet<>(Arrays.asList(banned));
    
            String[] wordList = paragraph.replaceAll("\\W+", " ").toLowerCase().split(" ");
    
            for (String w : wordList) {
                if(!ban.contains(w)) {
                    wordMap.put(w, wordMap.getOrDefault(w, 0) + 1);
                }
            }
    
            return Collections.max(wordMap.entrySet(), Map.Entry.comparingByValue()).getKey();
        }

    - replaceAll("\\W+", " ") : 연속되는 문자가 아닌 것들을 공백으로 대체

     

    (1) map.entrySet().stream().max(Map.Entry.comparingByValue)

    (2) Collections.max(wordMap.entrySet(), Map.Entry.comparingByValue()).getKey()

    Map 엔트리에서 최대값을 찾는 방식이다.

    - entrySet() : 맵의 모든 키-값 쌍이 포함된 Set을 반환한다.

    - stream() : Map의 엔트리 집합에서 스트림을 생성한다. 

    - max() : 스트림의 요소를 비교하여 최대값을 반환

    - Map.Entry.comparingByValue() : Map.Entry의 객체 값을 기준으로 비교하는 comparator를 반환한다. 각 엔트리값을 비교하여 최대값을 결정하는 데 사용됨 (기준이 되는 역할)

    - getKey() : Optinal에서 Key값을 가져옴

     

    메서드 레퍼런스 (method reference)

    특정 클래스의 메서드를 간단하게 참조할 수 있도록 한 문법이다.

    className::methodName 의 방식으로 사용한다.

    예시 )

    Map.Entry::getKey() ; Map.Entry 클래스의 getKey() 메서드를 사용

    .map(String::length) ; 각 문자열의 길이를 가져온다.

    .forEach(System.out::println) ; 각 문자열을 출력

     

    Stream API

    다양한 컬렉션과 데이터 소스에서 사용할 수 있는 편리한 문법이다.

    사용 가능한 곳

    - 컬렉션

    - 배열

    - 파일

    - Java8의 IntStream, LongStream, DoubleStream

    IntStream.range(1,5).forEach(System.out::println);

    처럼 사용 가능

Designed by Tistory.