Leetcode 1002. Find Common Characters, Java 解法

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. 1 <= A.length <= 100
  2. 1 <= A[i].length <= 100
  3. A[i][j] is a lowercase letter

Approach #1 dictionary

class Solution {
    public List<String> commonChars(String[] A) {
        List<String> ans = new ArrayList<>();
    
        // Common characters dictionary
        int[] dict = new int[26];
        for (int j = 0; j < A[0].length(); j++) {
            dict[A[0].charAt(j) - 'a']++;
        }
    
        for (int i = 1; i < A.length; i++) {
            
            // Dictionary of the current word
            int[] curr = new int[26];
            for (int j = 0; j < A[i].length(); j++) {
                curr[A[i].charAt(j) - 'a']++;
            }
            
            // Update the common dictionary
            for (int j = 0; j < 26; j++) {
                if (curr[j] < dict[j]) 
                    dict[j] = curr[j];
            }
        }
        
        for (int i = 0; i < 26; i++) {
            for (int j = 0; j < dict[i]; j++) {
                ans.add(Character.toString((char) ('a' + i)));
            }
        }
        return ans;
    }
}

先把所有String []A 里出现过的字母加到公共字典里,然后对String[] A里每一个String word, 用一个字典储存其每个字母出现过的次数,然后更新公共的字典。

这样一来,公共字典里储存的,都是每个word里字母至少出现的次数,如果没在其他word出现过,会被设为0.

Time: O(n), where n is the total number of characters in A;
extra space: O(1), excludes output/return space.

 

Approach #2  与上一方法思想类似,代码更简洁

    public List<String> commonChars(String[] A) {
        List<String> ans = new ArrayList<>();
        int[] count = new int[26]; 
        Arrays.fill(count, Integer.MAX_VALUE);
        for (String str : A) {
            int[] cnt = new int[26];
            for (int i = 0; i < str.length(); ++i) { ++cnt[str.charAt(i) - 'a']; } // count each char's frequency in string str.
            for (int i = 0; i < 26; ++i) { count[i] = Math.min(cnt[i], count[i]); } // update minimum frequency.
        }
        for (char c = 'a'; c <= 'z'; ++c) {
            while (count[c - 'a']-- > 0) { ans.add("" + c); }
        }
        return ans;
    }

Time: O(n), where n is the total number of characters in A;
extra space: O(1), excludes output/return space.

Q: What does ++cnt[c - 'a']; mean?

A:count the frequency of chars in String str.

c : cnt[c - 'a']

'a': cnt['a' - 'a'] = cnt[0]
'b': cnt['b' - 'a'] = cnt[1]
'c': cnt['c' - 'a'] = cnt[2]
...
'z': cnt['z' - 'a'] = cnt[25]

if char c represents 'x', then cnt[c - 'a'] = cnt[23]. That is, when encountering char 'x', we increase cnt[23] by 1.

Therefore, after traversal of all chars in String str, we have the frequency (number of occurrence) of each char in cnt.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值