Most Frequent 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.

答案

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        Set<String> banned_set = new HashSet<String>();
        Map<String, Integer> map = new HashMap<String, Integer>();
        String ans = "";
        int ansfreq = 0;
        
        String paragraph2 = "";
        // Remove punctuations
        for(int i = 0; i < paragraph.length(); i++) {
            char c = paragraph.charAt(i);
            if(c != '.' && c != ',' && c != '!' && c != ':' && c != '(' && c != ')' && c != '?' && c != ';' && c != '\'')
                paragraph2 = paragraph2 + c;
        }
        
        for(String s :  banned) {
            banned_set.add(s);
        }
        // Split paragraph into words, remove all banned words
        String[] words = paragraph2.split(" ");
        for(String word : words) {
            String word_lower = word.toLowerCase();
            if(banned_set.contains(word_lower)) continue;
            Integer freq = (map.get(word_lower) == null)?0:map.get(word_lower);
            map.put(word_lower, freq + 1);
            if(freq + 1 > ansfreq) {
                ans = word_lower;
                ansfreq = freq + 1;
            }
        }
        return ans;        
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容