Question

819. 最常见的单词

题目描述

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/most-common-word/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Ideas

1、Answer( Java )

解法思路:正则表达式+字符串处理

⚡️Java split()

split() 方法根据匹配给定的正则表达式来拆分字符串

String[] split = paragraph.replaceAll("\\W+", " ").toLowerCase().split("\\s+");

必须用 \\ 来使用转义字符
转义字符后面带的 + 加号是指 —> 匹配一个或多个
\W	匹配任何非单词字符
\s  匹配任何空白字符,包括空格、制表符、换页符等
String[] split = paragraph.split("[!?',;. ]");

Javasplit()方法使用多种分隔符切分字符串
//方式一:使用中括号"[…]"
paragraph.split("[!?',;. ]");
//方式二:多个分隔符用 | 作为连字符
paragraph.split(";|,");

⚡️Arrays类的静态方法asList()

方法的参数是 可变形参数组,能够将 数组 转换为 集合

👍排除空串 "" 的干扰

if (Objects.equals(s, "")) {//remove the influence of ""
                continue;
            }

Code

/**
 * @author Listen 1024
 * @description 819. 最常见的单词(正则表达式+字符串处理)
 * @date 2022-04-17 16:23
 */
class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        String res = null;
        HashSet<String> set = new HashSet<>();//save the banned words
        ArrayList<String> list = new ArrayList<>();//save the words
        set.addAll(Arrays.asList(banned));
        //method 1
//       String[] split = paragraph.replaceAll("\\W+", " ").toLowerCase().split("\\s+");
		//method 2
        String[] split = paragraph.split("[!?',;. ]");
        int[] cnt = new int[split.length];//cnt (the index related to the list)
        for (String s : split) {
            if (Objects.equals(s, "")) {//remove the influence of ""
                continue;
            }
            String temp = s.toLowerCase();
            if (!list.contains(temp)) {
                list.add(temp);
                cnt[list.indexOf(temp)] = 1;
            } else {
                ++cnt[list.indexOf(temp)];
            }
        }
        for (String s : set) {
            if (list.contains(s)) {
                cnt[list.indexOf(s)] = 0;//set the number of the banned word is 0
            }
        }

        int max = 0;
        for (int i = 0; i < cnt.length; i++) {
            if (cnt[i] >= max) {
                max = cnt[i];
                res = list.get(i);
            }
        }
        return res;
    }
}