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”

it’s a very easily understanding problem.
just calculate the frequency of each of the word in a sentence except the word in banned list.
and the fasted way to check is throught hashset.

so the code will be as follows:

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        //since the delimiter in paragraph can be any kind of, so instead of using split(), we will process this paragraph one by one. but with powerful regex, we can made it
        paragraph = paragraph.trim();
        String[] words = paragraph.replaceAll("[^A-Za-z]", " ").split("\\s+");
        
        HashSet<String> set = new HashSet<>();
        for (String word: banned) {
            set.add(word);
        }
        //now make all words in paragraph into lowcase
        for (String word: words) {
            word = word.toLowerCase();
            //System.out.println(word);
        }
        //use hashmap to calculate the frequency of each words, and maintain few variables to get the result
        HashMap<String, Integer> map = new HashMap<>();
        int times = 0;
        String res = "";
        for (String word: words) {
            
            if (set.contains(word)) continue;
            map.put(word, map.getOrDefault(word, 0) + 1);
            if (map.get(word) > times) {
                times = map.get(word);
                res = word;
            }
        }
        //System.out.println(map.get("ball"));
        return res;
    }
}

then why the fuck this code can’t working?

posted @ 2020-09-13 09:20  EvanMeetTheWorld  阅读(37)  评论(0)    收藏  举报