刷題日記(16)Most Common Word
Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn’t banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.
Example:
Input:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.
Note:
1 <= paragraph.length <= 1000
.0 <= banned.length <= 100
.1 <= banned[i].length <= 10
.- 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.) paragraph
only consists of letters, spaces, or the punctuation symbols!?',;.
- There are no hyphens or hyphenated words.
- Words only consist of letters, never apostrophes or other punctuation symbols.
解題思路:
- 把ban list變成arraylist放入set中
- 處理傳進來文字放進list,使用replaceable(“\\pP”, “ ”)和split(“\\s+”)
- for loop比較出現次數和不在ban list中,增加值放入hashmap裡
- 記得最重要的比較部分Collections.max (count.entrySet(), Map.Entry.comparingByValue())
- 最後return 4的element的getkey
<main function>
- 先設一個Hashset叫ban,然後把傳進來的 banned list變成Array List放入ban中
- 再設一個HashMap叫count
- 再設一個String List叫words 然後把傳進來要處理的paragraph先用replaceable(“\\pP”, “ ”),把所有的標點符號換成空格,之後再toLowerCase,最後split(“\\s+”),任意空格數皆可分開,然後把paragraph傳進string List,這樣子就把文字段落完美的一個一個分開裝進去了
- 接著再用for loop把string一個一個從上面剛裝滿的list裡面拿出來
4.1 如果ban中不含該string,接著判斷他有沒有在count這個hashpmap中,使用count.getOrDefault如果沒有就返回0,如果有就拿到該值加+1再用count.put放回去
5. 最後return Collection.max() 這個裡面放入 count.entrySet, 和map.Entry.comparingByValue, 他們會iteration map和返回最大的element
6. 最後用getKey得到該element的key
