0
点赞
收藏
分享

微信扫一扫

Leetcode笔记 每日一题 819. 最常见的单词 (22.04.17)

驚鴻飛雪 2022-04-17 阅读 52

Leetcode笔记 每日一题 819. 最常见的单词 (22.04.17)

Leetcode 每日一题 819. 最常见的单词 (22.04.17)

一、题目

给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。返回出现次数最多,同时不在禁用列表中的单词。

题目保证至少有一个词不在禁用列表中,而且答案唯一。

禁用列表中的单词用小写字母表示,不含标点符号。段落中的单词不区分大小写。答案都是小写字母。

示例:

提示:

二、解题思路

(一) 方法:哈希表计数

(二)一刷:Python代码

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        paragraph = paragraph.lower() + "."
        res = [] # 用列表res来存储单词
        hash = {} 
        words = ""
        # 提取单词
        for i in paragraph:
            if i in ['!','?',"'", ",",";","."," "]:
                if len(words) > 0:
                    res.append(words)
                    words = ""
            else:
                words += i
        # 哈希表计数
        for word in res:
            if word not in banned:
                if word in hash:
                    hash[word] += 1
                else:
                    hash[word] = 1
        # 求出出现次数最多的单词
        count = max(hash.values())
        for w in hash:
            if hash[w] == count:
                return w

(三)二刷

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        hash={}
        for i in ['!','?',"'", ",",";","."]:
            paragraph = paragraph.replace(i,' ')
        words = paragraph.lower().split()
        
        for word in words:
            if word not in banned:
                if word in hash:
                    hash[word] += 1
                else:
                    hash[word] = 1
        count = max(hash.values())
        for w in hash:
            if hash[w]== count:
                return w

(四)参考题解中的方法:用Counter函数和正则表达式

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        return max(Counter(re.split(r"[ ,.!?';]", paragraph.lower())).items(), key=lambda x:(len(x) > 0, x[0] not in b, x[1]))[0] if (b := set(banned + [""])) else ""

参考题解:作者:Benhao 《[Python/Java/JavaScript/Go] 模拟》

举报

相关推荐

0 条评论