알고리즘/Array

가장 흔한 단어

e-pd 2023. 9. 29. 00:15

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

 

LeetCode - The World's Leading Online Programming Learning Platform

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

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        if (paragraph == null || paragraph.isBlank()) {
            return null;
        }
        // replace
              String replaced = paragraph.replaceAll("[^A-Za-z]+", " ");
        List<String> bannedList = Arrays.asList(banned);

        return Arrays.stream(replaced.split(" "))
                .map(String::toLowerCase)
                .filter(Predicate.not(bannedList::contains))
                .filter(Predicate.not(String::isBlank))
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream()
                .max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse(null);
    }
}

 

 

혹은 정규식: (\\W+) 사용.

getOrDefault로 전개할 수도 있음.