leetcode Most Common Word——就是在考察自己实现split
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的更多相关文章
- [LeetCode] Most Common Word 最常见的单词
Given a paragraph and a list of banned words, return the most frequent word that is not in the list ...
- LeetCode – Most Common Word
Given a paragraph and a list of banned words, return the most frequent word that is not in the list ...
- 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 ...
- leetcode面试准备: Word Pattern
leetcode面试准备: Word Pattern 1 题目 Given a pattern and a string str, find if str follows the same patte ...
- [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 ...
- [LeetCode] 243. Shortest Word Distance 最短单词距离
Given a list of words and two words word1 and word2, return the shortest distance between these two ...
- [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 ...
- [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 ...
- 【Leetcode_easy】819. Most Common Word
problem 819. Most Common Word solution: class Solution { public: string mostCommonWord(string paragr ...
随机推荐
- Spring3.x 版本和 JDK1.8 不兼容导致 java.lang.IllegalStateException: Failed to load ApplicationContext
由于安装了 JDK1.8 的版本,最近在进行整合 Struts2+Spring+Hibernate 框架的时候,不小心导入了之前下载的 Spring 3.2.0 版本的 jar 包. 结果在运行测试用 ...
- Java转义形如nbsp;的HTML编码
需要引用一个maven <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <d ...
- 【Ruby】【改gem源镜像】【Win10 + Jruby-9.1.2.0 + Rails 5.1.3 + gem 2.6.4 】
参考地址:https://ruby-china.org/topics/33843 (1)> gem sources --add http://gems.ruby-china.org 遇到问题: ...
- 利用angularjs完成注册表单
ng-init="username = 'first'"设置初始显示first字段 ng-class="{'error':signUpForm.username.$inv ...
- bzoj 1036: [ZJOI2008]树的统计Count 树链剖分+线段树
1036: [ZJOI2008]树的统计Count Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 16294 Solved: 6645[Submit ...
- eclipse maven maven-compiler-plugin 报错 完全解决
报错如下: Maven install失败 Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:comp ...
- [转]C++中const、volatile、mutable的用法
原文:https://blog.csdn.net/imJaron/article/details/79657642 const意思是“这个函数不修改对象内部状态”. 为了保证这一点,编译器也会主动替你 ...
- List<String> list=new ArrayList<String>(20);为什么要声明为List 而不是ArrayList<String>?
如何理解:List<String> list=new ArrayList<String>();为甚麼要声明为List 而不是ArrayList<String>? 在 ...
- vue模板编译
Vue 的模板编译是在 $mount 的过程中进行的,在 $mount 的时候执行了 compile 方法来将 template 里的内容转换成真正的 HTML 代码. complie 最终生成 re ...
- leecode第七十题(爬楼梯)
class Solution { public: int climbStairs(int n) { vector<unsigned long long> num;//斐波那契数列 num. ...