819. 最常见的单词(正则表达式+字符串处理)

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;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值