首页 > 其他分享 >leetcode Most Common Word——就是在考察自己实现split

leetcode Most Common Word——就是在考察自己实现split

时间:2023-05-30 17:31:50浏览次数:39  
标签:Word String str banned Most paragraph Common words word

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]

 

标签:Word,String,str,banned,Most,paragraph,Common,words,word
From: https://blog.51cto.com/u_11908275/6381042

相关文章

  • 如何将word公式粘贴到FCKEditor里面
    ​ 这种方法是servlet,编写好在web.xml里配置servlet-class和servlet-mapping即可使用后台(服务端)java服务代码:(上传至ROOT/lqxcPics文件夹下)<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@     page contentType="text/html;cha......
  • android开发java.lang.NoClassDefFoundError: org/jetbrains/kotlin/cli/common/Prope
    问题:编译Android项目出现java.lang.NoClassDefFoundError:org/jetbrains/kotlin/cli/common/PropertiesKt原因:项目使用发JDK版本和Kotlin版本不一致或者说不对应导致gradle找不到对应的类解决方法:我的解决方法是降低JDK的版本到1.8,具体操作是OpenModulesSettings->SDKLoc......
  • 如何将word公式粘贴到xhEditor里面
    ​ 在之前在工作中遇到在富文本编辑器中粘贴图片不能展示的问题,于是各种网上扒拉,终于找到解决方案,在这里感谢一下知乎中众大神以及TheViper。通过知乎提供的思路找到粘贴的原理,通过TheViper找到粘贴图片的方法。其原理为一下步骤:监听粘贴事件;【用于插入图片】获取光标位置;【......
  • 文档在线预览(二)word、pdf文件转html以实现文档在线预览
    @目录一、将文件转换成html字符串1、将word文件转成html字符串2、将pdf文件转成html字符串二、将文件转换成html,并生成html文件FileUtils类将html字符串生成html文件示例:1、将word文件转换成html文件2、将pdf文件转换成html文件实现文档在线预览的方式除了上篇文章《文档在线预览......
  • WordCount案例实操
    WordCount案例实操java代码WordCountMapper类packagecom.guodaxia.mapreduce.wordcount;importorg.apache.hadoop.io.IntWritable;importorg.apache.hadoop.io.LongWritable;importorg.apache.hadoop.io.Text;importorg.apache.hadoop.mapreduce.Mapper;importjav......
  • 渗透---WordPress网站
    WordPress简介WordPress是使用PHP语言开发的博客平台,用户可以在支持PHP和MySQL数据库的服务器上架设属于自己的网站。也可以把WordPress当作一个内容管理系统(CMS)来使用。WordPress是一款个人博客系统,并逐步演化成一款内容管理系统软件,它是使用PHP语言和MySQL数据库开发的,用......
  • 渗透--WordPress网站
    WordPress简介WordPress是使用PHP语言开发的博客平台,用户可以在支持PHP和MySQL数据库的服务器上架设属于自己的网站。也可以把WordPress当作一个内容管理系统(CMS)来使用。WordPress是一款个人博客系统,并逐步演化成一款内容管理系统软件,它是使用PHP语言和MySQL数据库开发的,用......
  • 如何将word公式粘贴到TinyMCE里面
    ​ ueditor粘贴不能粘贴word中的图片是一个很头疼的问题,在我们的业务场景中客户要求必须使用ueditor并且支持word的图片粘贴,因为这个需求头疼了半个月,因为前端方面因为安全的原因是不允许访问本地文件的。首先说一下,ueditor粘贴word图片的问题已经解决,但是不是纯web方法解决的,......
  • 如何将word公式粘贴到帝国CMS里面
    ​ 图片的复制无非有两种方法,一种是图片直接上传到服务器,另外一种转换成二进制流的base64码目前限chrome浏览器使用首先以um-editor的二进制流保存为例:打开umeditor.js,找到UM.plugins['autoupload'],然后找到autoUploadHandler方法,注释掉其中的代码。加入下面的代码://判断剪......
  • 如何将word公式粘贴到动易CMS里面
    ​ 这种方法是servlet,编写好在web.xml里配置servlet-class和servlet-mapping即可使用后台(服务端)java服务代码:(上传至ROOT/lqxcPics文件夹下)<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@     page contentType="text/html;cha......