-
[string] most common wordAlgorithm/LeetCode 2025. 3. 9. 11:28
✅ Problem
https://leetcode.com/problems/most-common-word/description/
✅ Approach & Solution
방식)
더보기- 값 필터링 우선 수행하여 비교 대상 개수 줄이기
- banned에 포함되지 않는 값들에 대해서만 등장 횟수 계산
- Set의 contains() 사용
- Map을 사용해 정렬
class Solution { public String mostCommonWord(String paragraph, String[] banned) { // symbol 제외한 대상 문자열만 뽑아내기 String[] words = paragraph.replaceAll("\\W+", " ").toLowerCase().split(" "); // Map 사용해 등장 횟수 count Set<String> bannedSet = new HashSet<>(Arrays.asList(banned)); Map<String, Integer> wordMap = new HashMap<>(); for (String word : words) { if (!bannedSet.contains(word)) { wordMap.put(word, wordMap.getOrDefault(word, 0) + 1); } } // Map 사용해 정렬 return Collections.max(wordMap.entrySet(), Map.Entry.comparingByValue()).getKey(); } }
'Algorithm > LeetCode' 카테고리의 다른 글
[stack] valid parentheses (0) 2025.03.23 [array] container with most water (0) 2025.03.22 [string] reorder data in log files (0) 2025.03.09 [string] reverse string (0) 2025.03.08 [string] valid palindrome (0) 2025.03.08 - 값 필터링 우선 수행하여 비교 대상 개수 줄이기