819. 最常见的单词

2023-12-14 17:13:40

819. 最常见的单词
在这里插入图片描述


Java:split() 过滤

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        String s = paragraph.replaceAll("\\p{Punct}", " ");  // 去除所有标点符号
        String arr[] = s.split(" +");  // "a, a, a, a, b,b,b,c, c" 遇到这种案例就很恶心,不按照正规的格式来出牌!
        Map<String, Integer> map = new HashMap<>();
        Set<String> set = new HashSet<>();
        for (String str : banned) {
            set.add(str);
        }
        for (int i = 0; i < arr.length; ++i) {
            String ss = arr[i].toLowerCase();
            if (!set.contains(ss)) {
                map.put(ss, map.getOrDefault(ss, 0) + 1);
            }
        }
        List<String> list = new ArrayList<>(map.keySet());
        Collections.sort(list, (a, b) -> map.get(b).compareTo(map.get(a)));
        
        return list.get(0);
    }
}

Java:直接筛选字符

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        Set<String> bannedSet = new HashSet<String>();
        for (String word : banned) {
            bannedSet.add(word);
        }
        int maxFrequency = 0;
        Map<String, Integer> frequencies = new HashMap<String, Integer>();
        StringBuffer sb = new StringBuffer();
        int length = paragraph.length();
        for (int i = 0; i <= length; i++) {
            if (i < length && Character.isLetter(paragraph.charAt(i))) {
                sb.append(Character.toLowerCase(paragraph.charAt(i)));
            } else if (sb.length() > 0) {
                String word = sb.toString();
                if (!bannedSet.contains(word)) {
                    int frequency = frequencies.getOrDefault(word, 0) + 1;
                    frequencies.put(word, frequency);
                    maxFrequency = Math.max(maxFrequency, frequency);
                }
                sb.setLength(0);
            }
        }
        String mostCommon = "";
        Set<Map.Entry<String, Integer>> entries = frequencies.entrySet();
        for (Map.Entry<String, Integer> entry : entries) {
            String word = entry.getKey();
            int frequency = entry.getValue();
            if (frequency == maxFrequency) {
                mostCommon = word;
                break;
            }
        }
        return mostCommon;
    }
}

文章来源:https://blog.csdn.net/LIZHUOLONG1/article/details/134998006
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。