Monday, January 7, 2019
819. Most Common Word
class Solution {
public String mostCommonWord(String paragraph, String[] banned) {
Map<String, Integer> map = new HashMap<>();
Set<String> set = new HashSet<>(Arrays.asList(banned));
String[] strs = paragraph.toLowerCase().split("!|\\?|'|,|;|\\.|\\s+");
int max = 0;
for (String s : strs) {
if (s.length() > 0 && !set.contains(s)) {
int count = 1 + map.getOrDefault(s, 0);
max = Math.max(max, count);
map.put(s, count);
}
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == max) {
return entry.getKey();
}
}
return null;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment