The World Best ST.

LEETCODE-查找常用字符串

字数统计: 303阅读时长: 1 min
2019/12/21 Share

LEETCODE-查找常用字符串

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

示例 1:

输入:[“bella”,”label”,”roller”]

输出:[“e”,”l”,”l”]

示例 2:

输入:[“cool”,”lock”,”cook”]

输出:[“c”,”o”]

思路:通过交集获取

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
26
27
28
29
30
31
32
public static List<String> commonChars(String[] A) {
List<String> resultList = new ArrayList<>();
if (A == null || A.length < 2) {
return resultList;
}
int[] ansArray = new int[26];
for (int i = 0; i < 26; i ++) {
ansArray[i] = Integer.MAX_VALUE;
}
for (String s : A) {
int[] tmp = new int[26];
for (int i = 0; i < 26; i ++) {
tmp[i] = 0;
}
for (char c : s.toCharArray()) {
// 计算每个字符串中每个字符出现的次数
tmp[c - 'a'] ++;
}
for (int i = 0; i < 26; i ++) {
// 获取每个字符出现的最小值
ansArray[i] = Math.min(tmp[i], ansArray[i]);
}
}
for (int i = 0; i < 26; i ++) {
while (ansArray[i] > 0) {
// 将结果输出
resultList.add(""+(char)(i + 'a'));
ansArray[i] --;
}
}
return resultList;
}

参考资料:

https://leetcode-cn.com/problems/find-common-characters

CATALOG
  1. 1. LEETCODE-查找常用字符串