LeetCode1002-查找常用字符

题目链接

英文链接:https://leetcode.com/problems/find-common-characters/

中文链接:https://leetcode-cn.com/problems/find-common-characters/

题目详述

给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。

你可以按任意顺序返回答案。

示例 1:

1
2
输入:["bella","label","roller"]
输出:["e","l","l"]

示例 2:

1
2
输入:["cool","lock","cook"]
输出:["c","o"]

提示:

  1. 1 <= A.length <= 100
  2. 1 <= A[i].length <= 100
  3. A[i][j] 是小写字母

题目详解

  • 对字符串数组中的每个字符取交集,结果允许重复,类似于 LeetCode350-两个数组的交集II
  • 因为只包含小写字母,可以用一个大小为 26 的数组进行统计。
  • 遍历每个字符串,取字符交集,即取个数较小者。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class LeetCode_01002 {

public List<String> commonChars(String[] A) {
int[] cnt = new int[26];
for (char c : A[0].toCharArray()) {
++cnt[c - 'a'];
}
for (int i = 1; i < A.length; ++i) {
int[] count = new int[26];
for (char c : A[i].toCharArray()) {
++count[c - 'a'];
}
for (int j = 0; j < 26; ++j) {
cnt[j] = Math.min(cnt[j], count[j]);
}
}
List<String> res = new ArrayList<>();
for (int i = 0; i < 26; ++i) {
for (int j = 0; j < cnt[i]; ++j) {
res.add(String.valueOf((char) ('a' + i)));
}
}
return res;
}
}