zoukankan      html  css  js  c++  java
  • [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 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.

    给一段文字和一个禁止的单词列表,找出文段中出现最多的单词。题目难度不大,主要是如何处理字符串。

    解法:先对文字进行处理,分拆成单词并转为小写。然后统计所有不在禁止单词表里的单词出现次数。最后在返回出现次数最多的单词。

    Java:

    public String mostCommonWord(String p, String[] banned) {
            Set<String> ban = new HashSet<>(Arrays.asList(banned));
            Map<String, Integer> count = new HashMap<>();
            String[] words = p.replaceAll("\pP" , " ").toLowerCase().split("\s+");
            for (String w : words) if (!ban.contains(w)) count.put(w, count.getOrDefault(w, 0) + 1);
            return Collections.max(count.entrySet(), Map.Entry.comparingByValue()).getKey();
        }
    

    Python:

    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]
    

    Python:

    def mostCommonWord(self, paragraph, banned):
            ban = set(banned)
            paragraph = [s.strip("!?',;.") for s in paragraph.lower().split(' ')]        
            p = [w for w in paragraph if w not in ban]
            word_count = {w: 0 for w in p}
            for w in p:
                word_count[w] += 1
            return max(word_count, key=lambda k: word_count[k])  

    Python: wo

    import collections
    import string
    
    class Solution(object):
        def mostCommonWord(self, paragraph, banned):
            """
            :type paragraph: str
            :type banned: List[str]
            :rtype: str
            """
            words = [
                word.lower().rstrip(string.punctuation)
                for word in paragraph.split()
            ]
            m = collections.Counter()
            for word in words:
                if word not in banned:
                    m[word] += 1
            res = []
            mx = 0
            for k in m:
                if m[k] > mx:
                    mx = m[k]
           
            for k in m:
                if m[k] == mx:
                    res.append(k)
            return res[0]   

    C++:

    class Solution {
    public:
         string mostCommonWord(string p, vector<string>& banned) {
            unordered_set<string> ban(banned.begin(), banned.end());
            unordered_map<string, int> count;
            for (auto & c: p) c = isalpha(c) ? tolower(c) : ' ';
            istringstream iss(p);
            string w;
            pair<string, int> res ("", 0);
            while (iss >> w)
                if (ban.find(w) == ban.end() && ++count[w] > res.second)
                    res = make_pair(w, count[w]);
            return res.first;
        }
    };
    

        

      

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    控制一个cell不可被移动到另外一个section中
    core data 手动修改 .xcodatamodeld 文件 和 po 生成的 模型类 注意事项
    stringByTrimmingCharactersInSet 取出string 前后空格
    项目架构简述
    nil NULL [NSNULL null]
    如何定义一个应用之间调用的ios 本地URL
    UITableView隐藏多余的分割线
    解决UItableView cell的间隔线 separatorStyle ( plain group 两种类型)
    模拟器 真机 测试 内存消耗 资源对比
    微服务架构:Eureka集群搭建
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9649770.html
Copyright © 2011-2022 走看看