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. 前端UI框架总结

    H-ui 前端框架 架起设计与后端的桥梁轻量级前端框架,简单免费,兼容性好,服务中国网站. 官网:http://www.h-ui.net/H-ui.admin.shtml github下载:https ...

  2. _itemmod_add

    命令._add items XXX 为目标添加一组物品 `comment`  备注 `categoryId` 组ID `entry` 物品entry `count`数量

  3. SqlServer中exists和in的区别

    1.in 2.exists

  4. MySQL的正则表达式的LIKE和REGEXP区别

    LIKE匹配整个列.如果被匹配的文本在列值 中出现,LIKE将不会找到它,相应的行也不被返回(除非使用 通配符).而REGEXP在列值内进行匹配,如果被匹配的文本在 列值中出现,REGEXP将会找到它 ...

  5. PyMongo官方文档翻译——VNPY

    PyMongo是MongoDB数据库的python模块 VNPY默认的数据库,没有采用SQL类型的数据库,而是采用No-Sql类型的MongoDB数据库, 对于想了解VNPY内部结构的童鞋,多多少少会 ...

  6. English trip V1 - B 20. Likes and Dislikes 喜欢和不喜欢 Teacher:Sole Key:

    In this lesson you will learn to talk about likes and dislikes. 课上内容(Lesson) # talk about hobby Do y ...

  7. anaconda安装tensorflow

    1.下载anaconda python3.5版本,Windows不支持python3.6,linux和mac支持python2.7和python3.3+ 2.创建环境   conda create - ...

  8. adobe

    使用adobe acrobat pro dc可以处理pdf,自动识别,编辑pdf,将pdf导出为word.(收费可破解)

  9. vue select的change事件,将点击过的城市名存在数组中,下次调用不需要再调用接口

    <template> <div id="body" class="application" v-show="show" v ...

  10. 小程序获取openid 小程序授权

    小程序获取openid 小程序可以通过微信官方提供的登录能力方便地获取微信提供的用户身份标识,快速建立小程序内的用户体系. wx.login(Object object) 调用接口获取登录凭证(cod ...