819. 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"
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.
class Solution(object):
def split_word(self, paragraph):
sep = set("[!?',;.] ")
ans = []
pos = 0
for i,c in enumerate(paragraph):
if c in sep:
word = paragraph[pos:i]
if word:
ans.append(word)
pos = i+1
word = paragraph[pos:]
if word:
ans.append(word)
return ans def mostCommonWord(self, paragraph, banned):
"""
:type paragraph: str
:type banned: List[str]
:rtype: str
"""
m = {}
paragraph = paragraph.lower()
for w in self.split_word(paragraph):
if w in banned: continue
m[w] = m.get(w, 0)+1
ans = ""
max_cnt = 0
for w,c in m.items():
if c > max_cnt:
ans = w
max_cnt = c
return ans

使用字符串替换也可以实现,就是找到哪些字符应该直接remove掉,然后再分割:

public static String mostCommonWord(String paragraph, String[] banned) {
String[] splitArr = paragraph.replaceAll("[!?',;.]","").toLowerCase().split(" ");
HashMap<String, Integer> map = new HashMap<>();
List<String> bannedList = Arrays.asList(banned);
for(String str: splitArr) {
if(!bannedList.contains(str)) {
map.put(str, map.getOrDefault(str, 0) + 1);
}
} int currentMax = 0;
String res = "";
for(String key: map.keySet()) {
res = map.get(key) > currentMax ? key : res;
currentMax = map.get(key);
}
return res;
}

还有使用内置python的正则表达式:

Python:
Thanks to @sirxudi I change one line from
words = re.sub(r'[^a-zA-Z]', ' ', p).lower().split()
to
words = re.findall(r'\w+', p.lower()) def mostCommonWord(self, p, banned):
ban = set(banned)
words = re.findall(r'\w+', p.lower())
return collections.Counter(w for w in words if w not in ban).most_common(1)[0][0]

leetcode Most Common Word——就是在考察自己实现split的更多相关文章

  1. [LeetCode] Most Common Word 最常见的单词

    Given a paragraph and a list of banned words, return the most frequent word that is not in the list ...

  2. LeetCode – Most Common Word

    Given a paragraph and a list of banned words, return the most frequent word that is not in the list ...

  3. LeetCode 819. Most Common Word (最常见的单词)

    Given a paragraph and a list of banned words, return the most frequent word that is not in the list ...

  4. leetcode面试准备: Word Pattern

    leetcode面试准备: Word Pattern 1 题目 Given a pattern and a string str, find if str follows the same patte ...

  5. [leetcode]244. Shortest Word Distance II最短单词距离(允许连环call)

    Design a class which receives a list of words in the constructor, and implements a method that takes ...

  6. [LeetCode] 243. Shortest Word Distance 最短单词距离

    Given a list of words and two words word1 and word2, return the shortest distance between these two ...

  7. [LeetCode] 244. Shortest Word Distance II 最短单词距离 II

    This is a follow up of Shortest Word Distance. The only difference is now you are given the list of ...

  8. [LeetCode] 245. Shortest Word Distance III 最短单词距离 III

    This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as ...

  9. 【Leetcode_easy】819. Most Common Word

    problem 819. Most Common Word solution: class Solution { public: string mostCommonWord(string paragr ...

随机推荐

  1. mapgis IGServer账号

    2064803644@qq.com 1576391020@qq.com 密码一样

  2. springboot整合thymeleaf+tiles示例

    网上关于此框架的配置实在不多,因此想记录下来以防忘记 因为公司框架基于上述(公司采用gradle构建项目,楼主采用的是maven),所以楼主能少走些弯路: 1.创建springboot-maven项目 ...

  3. JS快速构建数组方法

    一.常用(普通)数组的构建 1.1 直接构建 let arr = ['mock1', 'mock2', 'mock3'] 1.2 通过new Array let arr = newArray('moc ...

  4. yum节省安装时间

    yum install java-1.8.0-openjdk 安装jdk yum install tomcat 安装tomcat wget http://repo.mysql.com/mysql-co ...

  5. DAY5 基本数据类型及内置方法

    一.可变与不可变数据类型 1.可变类型:值改变,但是id不变,证明就是在改变原值,是可变类型 2.不可变类型:值改变,但是id也跟着变,证明是产生了新的值,是不可变类型 二.数字类型 1.整型int ...

  6. python + lisp hy的新手注记2 eval, HyModel and python AST

    来自我在Stack Overflow上的提问,https://stackoverflow.com/questions/51675355/how-to-eval-a-cond-case-and-retu ...

  7. js常见知识点2.面向对象相关

    一.对象的概念 建议回复: 对象是一个整体,对外提供一些功能. 一切具有属性和方法的事物. 一切具有本质特征和行为的物质. 数据类型:       所有的基本数据类型都没有属性和方法.       所 ...

  8. Codeforces 939E - Maximize!

    939E - Maximize! 思路: 贪心:最后的集合是最大值+前k小个 因为平均值时关于k的凹形函数,所以可以用三分求最小值 又因为后面的k肯定比前面的k大,所以又可以双指针 三分: #incl ...

  9. vue element-ui 日期选择器组件 日期时间格式化

    vue element-ui 组件开发大大提高了我们的效率,但有时候并不能满足我们的需求,例如时间,日期组件: element-ui 日期返回的格式是这样的,看下图: 但我们要的是另一个格式 , 如下 ...

  10. (转)C#连接OleDBConnection数据库的操作

    对于不同的.net数据提供者,ADO.NET采用不同的Connection对象连接数据库.这些Connection对我们屏蔽了具体的实现细节,并提供了一种统一的实现方法. Connection类有四种 ...