Most Common Word
就是一道普通的处理字符串返回非banned的最高频字符串的题.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Solution { public String mostCommonWord(String paragraph, String[] banned) { Map<String, Integer> map = new HashMap<>(); String[] strs = paragraph.toLowerCase().trim().split("\\W+"); Set<String> b = new HashSet<>(); String res = ""; int count = Integer.MIN_VALUE; for(String s : banned) b.add(s); for(String s : strs) { if(b.contains(s)) //remove banned word first continue; else { map.put(s, map.getOrDefault(s, 0)+1); if(map.get(s) > count) { res = s; count = map.get(s); } } } return res; } } |