1002. Find Common Characters Easy
Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
Example 1:
1 | Input: ["bella","label","roller"] |
Example 2:
1 | Input: ["cool","lock","cook"] |
Note:
1 <= A.length <= 1001 <= A[i].length <= 100A[i][j]is a lowercase letter
思路:
思路一:暴力破解
仅供参考:
- 找到长度最小的字符串,由于是考虑每一个字符串中重复的元素
- 将这个字符串放到 map 中,map 中的值可以设为字符串数组长度
- 依次遍历,如果重复就 -1 ,最后看 map 中的值是否变为 0
思路二:哈希
可以结合下面的图和代码进行理解
- 由于都是小写字母,只需要使用容量为 26 的数组表示 26 位字母;
- 第一个 26 位数组,将字符串数组的第一个字符串装下,重复的 + 1
- 后面和第一个一样操作得到新的数组,比较其中的值,取
最小的即可,因为最小的那个才代表着它在自己的数组中重复了多少次,在所有的字符串中,它最多的字符重复 - 将结果放在第一个数组,继续比较

代码:
1 | public List<String> commonChars(String[] A) { |