๐Ÿฅž BE
home

819_Most Common Word

๋‹ด๋‹น์ž
์™„๋ฃŒ ์—ฌ๋ถ€
Solved
์š”์•ฝ
๋‚ ์งœ
2024/06/26
ํƒœ๊ทธ
๊ตฌํ˜„
๋ฌธ์ž์—ด
๋‚œ์ด๋„
Easy
์ถœ์ฒ˜
LeetCode

์ฝ”๋“œ

import java.util.*; class Solution { public String mostCommonWord(String paragraph, String[] banned) { Set<String> bans = new HashSet<>(Arrays.asList(banned)); // replaceAll() -> ํŠน์ˆ˜๋ฌธ์ž ๋ณ€ํ™˜. // ์†Œ๋ฌธ์ž ๋ณ€ํ™˜, ๊ณต๋ฐฑ ๊ธฐ์ค€ ๋ถ„๋ฆฌ String[] words = paragraph.replaceAll("\\W+", " ").toLowerCase().split(" "); // ๋‹จ์–ด ๊ฐœ์ˆ˜ ์ €์žฅ Map<String, Integer> counts = new HashMap<>(); // ๋‹จ์–ด ๋นˆ๋„์ˆ˜ ๊ณ„์‚ฐ for (String word : words) { if (!bans.contains(word)) { counts.put(word, counts.getOrDefault(word, 0) +1); } } // ๊ฐ€์žฅ ๋งŽ์ด ๋‚˜์˜จ ๋‹จ์–ด ์ฐพ๊ธฐ // counts ์—”ํŠธ๋ฆฌ์…‹์œผ๋กœ ๊ฐ€์ ธ์™€์„œ ๋น„๊ต ํ›„ key๊ฐ’ ๋ฆฌํ„ด String mostCommon = ""; int maxCount = 0; for (Map.Entry<String, Integer> entry : counts.entrySet()) { if (entry.getValue() > maxCount) { mostCommon = entry.getKey(); maxCount = entry.getValue(); } } return mostCommon; } }
Java
๋ณต์‚ฌ
\W : ๋ฌธ์ž๊ฐ€ ์•„๋‹Œ์• ๋“ค
+ : ์—ฐ์†์œผ๋กœ
์ „์ฒ˜๋ฆฌํ•œ ๋ฌธ์ž์—ด์„ ๊ธฐ์ค€์œผ๋กœ ๊ธˆ์ง€ ๋‹จ์–ด๋ฅผ ๋งคํ•‘ํ•˜๊ณ , ํ•ด์‰ฌ๋งต์œผ๋กœ ๋นˆ๋„์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค.
์ดํ›„ ๋งคํ•‘ํ•ด์ฃผ๋ฉด ๋.

๋ฌธ์ œ ํ•ด๊ฒฐ ์•„์ด๋””์–ด

1. ์ „์ฒ˜๋ฆฌ : ํŠน์ˆ˜๋ฌธ์ž ์ œ๊ฑฐ, ๋Œ€์†Œ๋ฌธ์ž ๊ตฌ๋ถ„x, ๊ณต๋ฐฑ๊ธฐ์ค€์œผ๋กœ ๋‹จ์–ด ๋ถ„๋ฆฌํ•˜๊ธฐ 2. ๊ธˆ์ง€ ๋‹จ์–ด ์ œ์™ธ ๋‘๊ฐœ๋งŒ ์ž˜ ํ•ด๊ฒฐํ•˜๋ฉด ๋‚˜๋จธ์ง€๋Š” ๋นˆ๋„์ˆ˜ ๊ณ„์‚ฐํ•˜๋ฉด ๋˜๋Š”๊ฑฐ๋ผ ์‰ฌ์› ๋‹ค.