给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
你可以按任意顺序返回答案。
示例1:
1 2
| 输入:["bella","label","roller"] 输出:["e","l","l"]
|
示例 2:
1 2
| 输入:["cool","lock","cook"] 输出:["c","o"]
|
提示:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] 是小写字母
来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
本题没有什么奇淫巧技,就老老实实遍历就行了。我们遍历A数组中的每个字符串,然后遍历每个字符串的每个字符,如果当前字符出现了,就在计数数组相应位置的值加一,接着和chars[]数组中对应字母出现次数进行比较,取较小的,这样比较下来,就会获得列表中的每个字符串中都显示的全部字符(有点最大公约数的意味),最后将结果加入链表返回即可,这里注意chars[]数组的索引即为当期字母 - 'a'的值,值为该字母出现的次数。
具体实现代码如下:
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 33 34 35 36
| class Solution { public List<String> commonChars(String[] A) { if (A == null) return new ArrayList<>();
int[] chars = new int[26]; int[] count = new int[26]; Arrays.fill(chars, Integer.MAX_VALUE);
for (int i = 0; i < A.length; i++) { for (char c : A[i].toCharArray()) { count[c - 'a']++; }
for (int j = 0; j < 26; j++) { chars[j] = Math.min(chars[j], count[j]); } Arrays.fill(count, 0); }
List<String> result = new ArrayList<>(); for (int i = 0; i < chars.length; i++) { if (chars[i] != 0) { int temp = chars[i]; for (int j = 0; j < temp; j++) { result.add(String.valueOf(Character.toChars(i + 'a'))); } } } return result; } }
|