MCPcopy
hub / github.com/qiyuangong/leetcode / mostCommonWord

Method mostCommonWord

java/819_Most_Common_Word.java:2–33  ·  view source on GitHub ↗
(String paragraph, String[] banned)

Source from the content-addressed store, hash-verified

1class Solution {
2 public String mostCommonWord(String paragraph, String[] banned) {
3 paragraph += ".";
4
5 Set<String> banset = new HashSet();
6 for (String word: banned) banset.add(word);
7 Map<String, Integer> count = new HashMap();
8
9 String ans = "";
10 int ansfreq = 0;
11
12 StringBuilder word = new StringBuilder();
13 for (char c: paragraph.toCharArray()) {
14 if (Character.isLetter(c)) {
15 // word
16 word.append(Character.toLowerCase(c));
17 } else if (word.length() > 0) {
18 // punctuation symbols
19 // node that word length should be larger than 0
20 String finalword = word.toString();
21 if (!banset.contains(finalword)) {
22 count.put(finalword, count.getOrDefault(finalword, 0) + 1);
23 // Record max here
24 if (count.get(finalword) > ansfreq) {
25 ans = finalword;
26 ansfreq = count.get(finalword);
27 }
28 }
29 word = new StringBuilder();
30 }
31 }
32 return ans;
33 }
34}

Callers

nothing calls this directly

Calls 4

addMethod · 0.45
toLowerCaseMethod · 0.45
putMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected