【力扣】1002. 查找常用字符

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

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

示例 1:

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

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

提示:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-common-characters

class Solution {
    public List<String> commonChars(String[] A) {
        Map<Character,Integer> map = new HashMap<Character,Integer>();

        for(int j =0; j < A[0].length(); j++){
            map.put(A[0].charAt(j),map.getOrDefault(A[0].charAt(j),0)+1);
        }

        for(int i = 1; i < A.length; i++){
            Map<Character,Integer> tempMap = new HashMap<Character,Integer>();
            for(int j =0; j < A[i].length(); j++){
                tempMap.put(A[i].charAt(j),tempMap.getOrDefault(A[i].charAt(j),0)+1);
            }
            map.forEach((key,value) -> {
                Integer tempValue = tempMap.get(key) == null ? 0 : tempMap.get(key);
            if(value > tempValue){
                map.put(key,tempValue);
            }
        });
        }
        List<String> result = new ArrayList<>();
        map.forEach((key,value) -> {
            if(value != 0){
                for(int i = 0; i < value; i++){
                    result.add(key+"");
                }
            }
        });
        return result;
    }
}
执行用时:28 ms, 在所有 Java 提交中击败了9.31%的用户
内存消耗:38.7 MB, 在所有 Java 提交中击败了95.48%的用户

问题点:使用了多个map,空间复杂度高

优化方式:使用简单数组能够比map更节省空间

一个入行不久的Java开发,越学习越感觉知识太多,自身了解太少,只能不断追寻
原文地址:https://www.cnblogs.com/fengtingxin/p/13818057.html