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.

思路:就是一个hashmap,注意split的时候需要\\W+ (any word character [a-zA-Z_0-9], occurs more than 1 times)

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        if(paragraph == null || banned == null ) {
            return null;
        } 
        String[] splits = paragraph.toLowerCase().split("\\W+");
        HashSet<String> banset = new HashSet<String>();
        for(String ban: banned) {
            banset.add(ban);
        }
        
        HashMap<String, Integer> hashmap = new HashMap<>();
        int maxcount = 0;
        String mostcommon = null;
        for(String str: splits) {
            String key = str.toLowerCase();
            if(banset.contains(key)) {
                continue;
            }
            hashmap.putIfAbsent(key, 0);
            hashmap.put(key, hashmap.get(key) + 1);
            if(hashmap.get(key) > maxcount) {
                maxcount = hashmap.get(key);
                mostcommon = key;
            }
        }
        return mostcommon;
    }
}
发布了663 篇原创文章 · 获赞 13 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/104859666