LeetCode-Find Common Characters

Description:
Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.

You may return the answer in any order.

Example 1:

Input: ["bella","label","roller"]
Output: ["e","l","l"]

Example 2:

Input: ["cool","lock","cook"]
Output: ["c","o"]

Note:

  • 1 <= A.length <= 100
  • 1 <= A[i].length <= 100
  • A[i][j] is a lowercase letter

题意:给定一个字符串数组S,要求找出数组中所有字符串相同的字符(如果相同的字符有多个也需要找出);

解法:假设最终的结果为res,那么res中的所有字符必然在所有元素中都有出现,也包括第一个字符串;那么,我们可以利用哈希表T存储第一个字符串的字符出现的次数,之后遍历这个字符串数组,为每个字符串都统计其字符出现的次数为哈希表M,此时,只需要修改T中字符出现的次数为Math.min(T中出现的次数,M中出现的次数)即可;最终,T中保留的就是所有字符串相同字符及其出现的次数;

Java
class Solution {
    public List<String> commonChars(String[] A) {
        Map<Character, Integer> common = new HashMap<>();
        frequency(common, A[0]);
        for (int i = 1; i < A.length; i++) {
            Map<Character, Integer> temp = new HashMap<>();
            frequency(temp, A[i]);
            for (char ch: common.keySet()) {
                common.put(ch, Math.min(common.get(ch), temp.getOrDefault(ch, 0)));
            }
        }
        List<String> res = new ArrayList<>();
        for (char ch: common.keySet()) {
            while (common.get(ch) > 0) {
                res.add("" + ch);
                common.put(ch, common.get(ch) - 1);
            }
        }
        
        return res;
    }
    
    private void frequency(Map<Character, Integer> common, String s) {
        for (int i = 0; i < s.length(); i++) {
            common.put(s.charAt(i), common.getOrDefault(s.charAt(i), 0) + 1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值