xiwenAndlejian / my-blog

Java基础学习练习题
1 stars 0 forks source link

1002. 查找常用字符串 #33

Open xiwenAndlejian opened 5 years ago

xiwenAndlejian commented 5 years ago

1002. 查找常用字符串

思路

输入:仅有小写字母组成的字符串数组A

输出:统计字符在所有字符串中出现的最小次数(N),返回数组中输出该字符N次。

解题

  1. 统计每个字符串中,各字符出现的次数。
  2. 统计各字符出现的最小次数。
  3. 根据最小次数输出数组。

代码

private static final int SIZE = 26;
// 输入字符串仅包含小写字符
public List<String> commonChars(String[] A) {
    int[] counter = new int[SIZE];
    for (int i = 0; i < SIZE; i++) counter[i] = Integer.MAX_VALUE;
    for  (int i = 0; i < A.length; i++) {
        int[] chars = new int[SIZE];
        for (char c: A[i].toCharArray()) {
            chars[c-'a']++;
        }
        for (int j = 0; j < SIZE; j++) {
            counter[j] = counter[j] < chars[j] ? counter[j] : chars[j];
        }
    }
    List<String> result = new LinkedList<>();
    for (int i = 0; i < SIZE; i ++) {
        char c = (char)('a' + i);
        for (int j = 0; j < counter[i]; j++) {
            result.add(c + "");
        }
    }
    return result;
}