1002.查找常用字符串

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] 是小写字母

参考网友的解题思路:
本题需要注意的是要输出所有单词中重复的字符,如果重复字符有多个就输出对应个数。我的解题思路如下:

  1. 以单词中的字符为key,字符在单词中的出现次数为value的Map将每个单词的字符及出现频次记录下来。
  2. 找出每个Map中key相同的元素,并以出现次数value的最小值为新的value组成重复单词出现频次的Map
  3. 遍历步骤2中的Map,根据value可以得知每个单词的出现次数,将Map转化为一个List

提交通过代码:
Java

class Solution {
    public List<String> commonChars(String[] A) {
        //res存放String[] A中重复出现的字符及次数
        Map<String,Integer> res=new HashMap();
        
        for(int i=0;i<A.length;i++) {
            String str=A[i];
            
            //map用于统计当前字符串中字符出现次数
            Map<String,Integer> map=new HashMap();
            
            for(int j=0;j<str.length();j++) {
                char ch=str.charAt(j);
                String temp=Character.toString(ch);
                if(map.containsKey(temp)){
                    //如果key存在,更新value加一
                    map.put(temp,map.get(temp)+1);
                } else {
                    //如果key不存在,第一次加入map,value值为1
                    map.put(temp,1);
                }
            }
            //判断是否是第一个字符串计数结果,如果是,将map数据存于res,如果不是,则需要更新某一字数在某一字符串中出现的最大次数
            if(i==0){
                //该方法用来追加另一个Map对象到当前Map集合对象,它会把另一个Map集合对象中的所有内容添加到当前Map集合对象。
                res.putAll(map);
            } else {
                Map<String,Integer> newMap=new HashMap();
                //使用Iterator遍历map,且使用泛型
                Iterator<Map.Entry<String,Integer>> iterator=res.entrySet().iterator();
                while(iterator.hasNext()){
                    Map.Entry<String,Integer> entry=iterator.next();
                    String key=entry.getKey();
                    Integer value=entry.getValue();
                    //判断是否更新计数
                    if(map.containsKey(key)) {
                        Integer tempValue=map.get(key);
                        newMap.put(key,Math.min(tempValue,value));
                    }
                }
                res=newMap;
            }
        }
        List<String> result=new ArrayList<>();
        for(Map.Entry<String,Integer> entry : res.entrySet()) {
            int value=entry.getValue();
            while(value!=0){
                result.add(entry.getKey());
                value--;
            }
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42956047/article/details/88368719