力扣题目:查找共同字符

时间:2024-04-29 22:40:26

    力扣题目:查找共同字符

开篇

题目链接: 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;
    }
}