力扣题目:查找共同字符

本文介绍了一种使用哈希表的方法来解决LeetCode题目1002,即查找给定字符串数组中的共同字符。代码首先初始化一个哈希表记录第一个字符串中每个字符的出现次数,然后遍历数组中的其他字符串,更新哈希表并找到最小值不为0的字母。最后,将这些字符添加到结果列表中返回。
摘要由CSDN通过智能技术生成

    力扣题目:查找共同字符

开篇

题目链接: 1002.查找共同字符

题目描述

在这里插入图片描述

代码思路

使用哈希表,记录每一个字母出现的次数,每次更新最小值,寻找最小值不为0到字母,添加到list列表中

代码纯享版

class Solution {
    public List<String> commonChars(String[] words) {
        List<String> list = new ArrayList();
        int[] hash = new int[26];
        for(int i = 0;  i < words[0].length(); i++){
            hash[words[0].charAt(i) - 'a']++;
        }
        for(int i = 0; i < words.length; i++){
            int[] temp = new int[26];
            for(int j = 0; j < words[i].length(); j++){
                temp[words[i].charAt(j) - 'a']++;
            }
            for(int k = 0; k < 26; k++){
                hash[k] = Math.min(temp[k], hash[k]);
            }
        }
        for (int i = 0; i < 26; i++) {
            while (hash[i] != 0) { 
                char c= (char) (i+'a');
                list.add("" + (char) (i+'a'));
                hash[i]--;
            }
        }
        return list;
    }
}

代码逐行解析版

class Solution {
    public List<String> commonChars(String[] words) {
        List<String> list = new ArrayList(); //用于最后结果的返回
        int[] hash = new int[26]; //创建hash数组作为字符哈希表(26个字母)
        for(int i = 0;  i < words[0].length(); i++){ //遍历第一个字符串的所有字符,初始化hash哈希表
            hash[words[0].charAt(i) - 'a']++; //对每个字符对应的下标加一
        }
        for(int i = 0; i < words.length; i++){ //遍历字符串数组words中所有的字符串
            int[] temp = new int[26]; //临时哈希表
            for(int j = 0; j < words[i].length(); j++){ //遍历该字符串的所有字符,初始化temp哈希表
                temp[words[i].charAt(j) - 'a']++;
            }
            for(int k = 0; k < 26; k++){ //遍历这两个哈希表,每个字母取哈希表
                hash[k] = Math.min(temp[k], hash[k]);
            }
        }
        for (int i = 0; i < 26; i++) { //遍历哈希表,对hash哈希表不为0的字符添加到list列表中
            while (hash[i] != 0) { // 注意这里是while,多个重复的字符
                char c= (char) (i+'a');
                list.add("" + (char) (i+'a'));
                hash[i]--;
            }
        }
        return list;
    }
}
  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值