LeetCode 1002. 查找共用字符

LeetCode 1002. 查找共用字符

描述

给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。

示例 1:

输入:words = [“bella”,“label”,“roller”]
输出:[“e”,“l”,“l”]

示例 2:

输入:words = [“cool”,“lock”,“cook”]
输出:[“c”,“o”]

提示:

1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] 由小写英文字母组成

题解

class Solution {
    public List<String> commonChars(String[] words) {
        if (words.length == 0) {
            // 没有单词 返回 空
            return new ArrayList<>();
        }
        // 存储小写字母出现情况
        int[] help = new int[26];
        // 用于存储结果
        List<String> res = new ArrayList<>();
        // 第一个单词出现的字母存储到help中
        for (int i = 0; i < words[0].length(); i++) {
            help[words[0].charAt(i) - 'a'] += 1;
        }
        // 遍历之后的每一个的单词
        for (int i = 1; i < words.length; i++) {
            // temp 记录当前单词与help字母同时出现情况
            int[] temp = new int[26];
            for (int j = 0; j < words[i].length(); j++) {
                if( help[words[i].charAt(j) - 'a'] != 0 
                &&  help[words[i].charAt(j)-'a'] > temp[words[i].charAt(j)-'a'] ) {
                    temp[words[i].charAt(j) - 'a']++;
                }
            }
            // 替换最新的公共字符
            help = temp;
        }
        // 根据存储的公共字符添加到结果中
        for(int i=0;i<26;i++){
            while ((help[i]--)!=0){
                res.add(Character.toString(i+'a'));
            }
        }
        // 返回结果
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值