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. 【C#】侦听文件系统更改通知 FileSystemWatcher 类

    using System; using System.IO; using System.Security.Permissions; public class Watcher { public stat ...

  2. char,String,int类型互转

    1.ascci码对应转换 字符,对应的ascii(其实是UTF-16)码:     char c='a'; int k=(int) c;    结果k=97 数字,对应的字符:     int k=9 ...

  3. STL_头文件

    #include <string> #include <vector> #include <deque> #include <queue> #inclu ...

  4. EditText取消焦点

    EditText取消焦点: 在父容器添加: android:focusable="true" android:focusableInTouchMode="true&quo ...

  5. 《剑指offer》第五十一题(数组中的逆序对)

    // 面试题51:数组中的逆序对 // 题目:在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组 // 成一个逆序对.输入一个数组,求出这个数组中的逆序对的总数. #include &l ...

  6. es6 Set 结合 Array.from 用法

    var arr=[1,2,3,2,3,4,5]; var set=new Set(arr) var arr1=Array.from(set) 重复数组  -  Set 化 (去重) - 转回数组 上述 ...

  7. Ajax请求导出Excel的问题

    文章转载自: http://yuwenlin.iteye.com/blog/2275289 Ajax请求导出Excel的问题描述: 前端发起Ajax请求get或post,后台使用Poi生成excel文 ...

  8. Android DatePickerDialog 使用方法

    (一)在Android 4.0以上系统的某些手机(如本人的测试机红米Note(系统4.4.4),以及模拟器(系统4.0)),使用如下代码创建时间选择器时,页面效果如图: Calendar cal = ...

  9. linux中tar命令(打包、压缩、解压)、zip和unzip、rar多种压缩文件

    一.名词解释 打包:将一大堆文件或目录变成一个总的文件[tar命令] 压缩:将一个大的文件通过一些压缩算法变成一个小文件[gzip,bzip2等] Linux中很多压缩程序只能针对一个文件进行压缩,这 ...

  10. 酷开 5.5 版本安装第三方app

    https://www.znds.com/jc/article/2952-1.html .开始安装(以安装当贝桌面为例): adb connect 192.168.XXX.XXX(电视IP) adb ...