1002. 查找共用字符

15 阅读1分钟

1002. 查找共用字符

相关企业

给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符(包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。

 

示例 1:

输入: words = ["bella","label","roller"]
输出: ["e","l","l"]

示例 2:

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

 

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] 由小写英文字母组成

解题答案

class Solution {
    public List<String> commonChars(String[] words) {
        int[] counts = null;
        for (String word : words) {
            counts = union(counts, count(word));
        }

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

    private int[] count(String s) {
        int[] count = new int[26];
        for (int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - 'a']++;
        }
        return count;
    }

    private int[] union(int[] count1, int[] count2) {
        if (count1 != null) {
            for (int i = 0; i < 26; i++) {
                count2[i] = Math.min(count2[i], count1[i]);
            }
        }
        return count2;
    }
}