leetcode-1002-easy

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.

思路一:用 26 长度的数组存储第一个词语的字母,然后依次对比后面的所有单词

    public List<String> commonChars(String[] words) {
        int[] pre = new int[26];
        int[] curr = new int[26];

        for (int i = 0; i < words[0].length(); i++) {
            pre[words[0].charAt(i) - 'a']++;
        }

        for (int i = 1; i < words.length; i++) {
            Arrays.fill(curr, 0);
            for (int j = 0; j < words[i].length(); j++) {
                curr[words[i].charAt(j) - 'a']++;
            }

            for (int k = 0; k < pre.length; k++) {
                pre[k] = Math.min(pre[k], curr[k]);
            }
        }

        List<String> result = new ArrayList<>();
        for (int i = 0; i < pre.length; i++) {
            while (pre[i] > 0) {
                result.add(String.valueOf((char) ('a' + i)));
                pre[i]--;
            }
        }

        return result;
    }
posted @ 2023-01-13 21:51  iyiluo  阅读(23)  评论(0)    收藏  举报