LeetCode 1002. 查找常用字符

目录结构

1.题目

2.题解


1.题目

给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。

你可以按任意顺序返回答案。

示例:

输入:["bella","label","roller"]
输出:["e","l","l"]


输入:["cool","lock","cook"]
输出:["c","o"]

提示:

  1. 1 <= A.length <= 100
  2. 1 <= A[i].length <= 100
  3. A[i][j] 是小写字母

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

2.题解

public class Solution1002 {

    @Test
    public void test1002() {
        String[] A = {"bella", "label", "roller"};
        System.out.println(commonChars(A));
    }

    public List<String> commonChars(String[] A) {
        List<String> result = new ArrayList<>();
        int[] count1 = new int[26], count2;
        for (char c : A[0].toCharArray()) {
            count1[c - 'a']++;
        }
        for (int i = 1; i < A.length; i++) {
            count2 = new int[26];
            for (char c : A[i].toCharArray()) {
                count2[c - 'a']++;
            }
            for (int j = 0; j < 26; j++) {
                count1[j] = Math.min(count1[j], count2[j]);
            }
        }
        for (int i = 0; i < 26; i++) {
            for (int j = 0; j < count1[i]; j++) {
                result.add(String.valueOf((char) ('a' + i)));
            }
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值