LeetCode 1002. Find Common Characters

Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists of lowercase English letters.

题目要求找数组里所有string的共同字符(含重复的)。刚开始想的是把第一个当成基准,把第一个的每个字符放到后面的string里找,如果没有就把它remove。看了解答以后才发现有更好的方法,维护一个dictionary,直接求每个字母在一个word中出现的次数的最小值。

class Solution {
    public List<String> commonChars(String[] words) {
        List<String> result = new ArrayList<>();
        
        int[] all = new int[26];
        for (int i = 0; i < 26; i++) {
            all[i] = 10000;
        }
        int[] count = new int[26];
        
        for (String word : words) {
            for (char c : word.toCharArray()) {
                count[c - 'a']++;
            }
            for (int i = 0; i < 26; i++) {
                all[i] = Math.min(count[i], all[i]);
                count[i] = 0;  // reset count
            }
        }

        for (int i = 0; i < 26; i++) {
            for (int j = 0; j < all[i]; j++) {
                result.add(String.valueOf((char)('a' + i)));
            }
        }
        
        return result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值