Skip to content

Latest commit

 

History

History
93 lines (65 loc) · 2.88 KB

0819._Most_Common_Word.md

File metadata and controls

93 lines (65 loc) · 2.88 KB

819. Most Common Word

难度: Easy

刷题内容

原题连接

内容描述

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.
 

Note:

1 <= paragraph.length <= 1000.
1 <= banned.length <= 100.
1 <= banned[i].length <= 10.
The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.)
paragraph only consists of letters, spaces, or the punctuation symbols !?',;.
Different words in paragraph are always separated by a space.
There are no hyphens or hyphenated words.
Words only consist of letters, never apostrophes or other punctuation symbols.

解题方案

思路 1 - 时间复杂度: O(N)- 空间复杂度: O(P)******

最需要注意的一个点就是,当input为下面的情况的时候,我们其实要将逗号也给分割开来

Input:
"a, a, a, a, b,b,b,c, c"
["a"]

Expected:
"b"

b,b,b,c其实是b b b c

思路就是先按照空格split,然后每个word再按照逗号split,最后strip掉每个word中所有的 !?';.等字符,还要注意全部换成小写

最后要注意就是我们以逗号split的时候可能会带入空word,后面要进行一下判断

因为paragraph中的每一个字符我们都要处理一次,时间复杂度就是O(N)

假设paragraph中有P个word,空间复杂度为O(P)

class Solution(object):
    def mostCommonWord(self, paragraph, banned):
        """
        :type paragraph: str
        :type banned: List[str]
        :rtype: str
        """
        banned = set(banned)
        words = [w.strip("!?';.") for word in paragraph.lower().split(' ') for w in word.split(',')]
        
        lookup = {}
        for word in words:
            if word and word not in banned: # 需要保证word不为空
                lookup[word] = lookup.get(word, 0) + 1
                
        max_freq = max(lookup.values())
        for key in lookup:
            if lookup[key] == max_freq:
                return key