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. 数据从mysql迁移至oracle时知识点记录(一)

    最近在做数据的迁移,再将数据从mysql迁移至oracle时,部分sql语句进行了修改,在此对部分知识点进行记录: 参考资料:https://dev.mysql.com/doc/refman/5.5/ ...

  2. 在使用Java8并行流时的问题分析

    最近在使用Java8的并行流时遇到了坑,线上排查问题时花了较多时间,分享出来与大家一起学习与自查 // 此处为坑 List<Java8Demo> copy = Lists.newArray ...

  3. http_load 高并发测试

    安装http_load 下载 sudo wget http://www.acme.com/software/http_load/http_load-09Mar2016.tar.gz 解压 sudo t ...

  4. scala函数式编程(一)

    scala函数编程特点: 1.Scala函数使用命名参数: 即函数参数传递的实参与函数名相对应,与函数位置不对应. object Test { def main(args: Array[String] ...

  5. java反编译器

    一时手残,把java工程中的源文件给删了,幸亏还有.class文件,想起java可以反编译,所以试一试. JD-Eclipse 如果是使用Eclipse的话,可以用Eclipse插件JadClipse ...

  6. vscode 常用扩展推荐

    1.扩展推荐 Beautify    Beautify code in place for VS Code CSS Formatter     Formatter for CSS ESLint     ...

  7. 网络通信框架:Netty和Mina

    参考: https://www.cnblogs.com/wrencai/p/5907042.html https://blog.csdn.net/qq_29954971/article/details ...

  8. Implicit super constructor Object() is undefined for default constructor. Must define an explicit constructor

    转自:https://blog.csdn.net/u013125680/article/details/43887987 解决方案:把java的类库加载进去,在工程上右键选择属性->Java B ...

  9. Python全栈开发-Day5-常用模块学习

    本节大纲: 模块介绍 time &datetime模块 random os sys shutil shelve xml处理 pyyaml处理 configparser hashlib re正则 ...

  10. 猫眼电影爬取(一):requests+正则,并将数据存储到mysql数据库

    前面讲了如何通过pymysql操作数据库,这次写一个爬虫来提取信息,并将数据存储到mysql数据库 1.爬取目标 爬取猫眼电影TOP100榜单 要提取的信息包括:电影排名.电影名称.上映时间.分数 2 ...