|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.HashSet; |
| 6 | +import java.util.Map; |
| 7 | +import java.util.Set; |
| 8 | + |
| 9 | +/** |
| 10 | + * 819. Most Common Word |
| 11 | +
|
| 12 | + Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. |
| 13 | + It is guaranteed there is at least one word that isn't banned, and that the answer is unique. |
| 14 | + Words in the list of banned words are given in lowercase, and free of punctuation. |
| 15 | + Words in the paragraph are not case sensitive. The answer is in lowercase. |
| 16 | +
|
| 17 | + Example: |
| 18 | + Input: |
| 19 | + paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." |
| 20 | + banned = ["hit"] |
| 21 | + Output: "ball" |
| 22 | + Explanation: |
| 23 | + "hit" occurs 3 times, but it is a banned word. |
| 24 | + "ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. |
| 25 | + Note that words in the paragraph are not case sensitive, |
| 26 | + that punctuation is ignored (even if adjacent to words, such as "ball,"), |
| 27 | + and that "hit" isn't the answer even though it occurs more because it is banned. |
| 28 | +
|
| 29 | + Note: |
| 30 | +
|
| 31 | + 1 <= paragraph.length <= 1000. |
| 32 | + 1 <= banned.length <= 100. |
| 33 | + 1 <= banned[i].length <= 10. |
| 34 | + The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.) |
| 35 | + paragraph only consists of letters, spaces, or the punctuation symbols !?',;. |
| 36 | + Different words in paragraph are always separated by a space. |
| 37 | + There are no hyphens or hyphenated words. |
| 38 | + Words only consist of letters, never apostrophes or other punctuation symbols. |
| 39 | + */ |
| 40 | +public class _819 { |
| 41 | + public static class Solution1 { |
| 42 | + public String mostCommonWord(String paragraph, String[] banned) { |
| 43 | + Set<String> bannedSet = new HashSet(Arrays.asList(banned)); |
| 44 | + String[] words = paragraph.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+"); |
| 45 | + Map<String, Integer> map = new HashMap<>(); |
| 46 | + Arrays.stream(words) |
| 47 | + .filter(word -> !bannedSet.contains(word)) |
| 48 | + .forEach(word -> map.put(word, map.getOrDefault(word, 0) + 1)); |
| 49 | + String result = ""; |
| 50 | + int freq = 0; |
| 51 | + for (String key : map.keySet()) { |
| 52 | + if (map.get(key) > freq) { |
| 53 | + result = key; |
| 54 | + freq = map.get(key); |
| 55 | + } |
| 56 | + } |
| 57 | + return result; |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments