819. 最常见的单词
Java:split() 过滤
class Solution {public String mostCommonWord(String paragraph, String[] banned) {String s = paragraph.replaceAll("\\p{Punct}", " "); // 去除所有标点符号String arr[] = s.split(" +"); // "a, a, a, a, b,b,b,c, c" 遇到这种案例就很恶心,不按照正规的格式来出牌!Map<String, Integer> map = new HashMap<>();Set<String> set = new HashSet<>();for (String str : banned) {set.add(str);}for (int i = 0; i < arr.length; ++i) {String ss = arr[i].toLowerCase();if (!set.contains(ss)) {map.put(ss, map.getOrDefault(ss, 0) + 1);}}List<String> list = new ArrayList<>(map.keySet());Collections.sort(list, (a, b) -> map.get(b).compareTo(map.get(a)));return list.get(0);}
}
Java:直接筛选字符
class Solution {public String mostCommonWord(String paragraph, String[] banned) {Set<String> bannedSet = new HashSet<String>();for (String word : banned) {bannedSet.add(word);}int maxFrequency = 0;Map<String, Integer> frequencies = new HashMap<String, Integer>();StringBuffer sb = new StringBuffer();int length = paragraph.length();for (int i = 0; i <= length; i++) {if (i < length && Character.isLetter(paragraph.charAt(i))) {sb.append(Character.toLowerCase(paragraph.charAt(i)));} else if (sb.length() > 0) {String word = sb.toString();if (!bannedSet.contains(word)) {int frequency = frequencies.getOrDefault(word, 0) + 1;frequencies.put(word, frequency);maxFrequency = Math.max(maxFrequency, frequency);}sb.setLength(0);}}String mostCommon = "";Set<Map.Entry<String, Integer>> entries = frequencies.entrySet();for (Map.Entry<String, Integer> entry : entries) {String word = entry.getKey();int frequency = entry.getValue();if (frequency == maxFrequency) {mostCommon = word;break;}}return mostCommon;}
}