关于leetcode:leetcode之最常见的单词

1次阅读

共计 1300 个字符,预计需要花费 4 分钟才能阅读完成。

本文次要记录一下 leetcode 之最常见的单词

题目

 给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。返回呈现次数最多,同时不在禁用列表中的单词。题目保障至多有一个词不在禁用列表中,而且答案惟一。禁用列表中的单词用小写字母示意,不含标点符号。段落中的单词不辨别大小写。答案都是小写字母。示例:输出: 
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
输入: "ball"
解释: 
"hit" 呈现了 3 次,但它是一个禁用的单词。"ball" 呈现了 2 次 (同时没有其余单词呈现 2 次),所以它是段落里呈现次数最多的,且不在禁用列表中的单词。留神,所有这些单词在段落里不辨别大小写,标点符号须要疏忽(即便是紧挨着单词也疏忽,比方 "ball,"),"hit" 不是最终的答案,尽管它呈现次数更多,但它在禁用单词列表中。提醒:1 <= 段落长度 <= 1000
0 <= 禁用单词个数 <= 100
1 <= 禁用单词长度 <= 10
答案是惟一的, 且都是小写字母 (即便在 paragraph 里是大写的,即便是一些特定的名词,答案都是小写的。)
paragraph 只蕴含字母、空格和下列标点符号!?',;.
不存在没有连字符或者带有连字符的单词。单词里只蕴含字母,不会呈现省略号或者其余标点符号。起源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/most-common-word
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

题解

class Solution {public String mostCommonWord(String paragraph, String[] banned) {Set<String> bannedSet = new HashSet<>();
        for (String ban : banned) {bannedSet.add(ban);
        }

        Map<String,Integer> countMap = new HashMap<>();
        String[] words = paragraph.toLowerCase().replaceAll("[^a-z]","").split("\\s+");
        for (String word : words) {if (bannedSet.contains(word)) {continue;}
            countMap.put(word, countMap.getOrDefault(word, 0) + 1);
        }

        int max = 0;
        String result = "";
        for (Map.Entry<String,Integer> entry : countMap.entrySet()) {if (max < entry.getValue()) {max = entry.getValue();
                result = entry.getKey();}
        }
        return result;
    }
}

小结

这里应用 Map 来统计单词,并应用 Set 来查问是否为禁用词,若为禁用词则不退出 Map 中统计,最初遍历 Map 取出计数最大的单词。

doc

  • 最常见的单词
正文完
 0