题目转载说明

作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/problems/find-common-characters/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

题目要求

给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。

示例

示例 1

输入:words = [“bella”,”label”,”roller”]
输出:[“e”,”l”,”l”]

示例 2

输入:words = [“cool”,”lock”,”cook”]
输出:[“c”,”o”]

题解

Java 题解

  1. class Solution {
  2. public List<String> commonChars(String[] words) {
  3. // 创建 count 数组用于记录字母出现的最小次数
  4. int[] count = new int[26];
  5. // 先任意选择一个词,这里选择第一个,把每个字母出现的次数进行统计
  6. for (char c : words[0].toCharArray()) {
  7. count[c - 'a'] += 1;
  8. }
  9. for (int i = 1; i < words.length; i++) {
  10. // 再创建一个数组,用于统计后面每个词的每个字母出现的次数
  11. int[] wordCount = new int[26];
  12. // 这个 for 用于统计
  13. for (int j = 0; j < words[i].length(); j++) {
  14. wordCount[words[i].charAt(j) - 'a'] += 1;
  15. }
  16. // 核心部分,对比两个数组的相同位置上的数,取相对小的出现的次数
  17. for (int k = 0; k < count.length; k++) {
  18. count[k] = Math.min(wordCount[k], count[k]);
  19. }
  20. }
  21. // 存结果
  22. ArrayList<String> res = new ArrayList<>();
  23. /*
  24. * 把 count 数组便利一边,然后通过 index + 'a' 的方式来得到字符
  25. * count[index] 表示的就是该字符出现的次数
  26. */
  27. for (int i = 0; i < count.length; i++) {
  28. if (count[i] > 0) {
  29. for (int j = 0; j < count[i]; j++) {
  30. res.add(String.valueOf((char)(i + 'a')));
  31. }
  32. }
  33. }
  34. return res;
  35. }
  36. }

Python 题解

  1. class Solution(object):
  2. def commonChars(self, A):
  3. res=[]
  4. if not A:
  5. return res
  6. # 先通过 set 去重,得到一组 key;需要明确知道的一点是,结果中出现的字母
  7. # 必然要出现在每一个单词中
  8. key=set(A[0])
  9. # 遍历这组 key
  10. for k in key:
  11. # 通过 a.count 得到每一个 key 在每个词中出现的次数,形成一个 list
  12. # 然后在 list 中取最小值即可,没有出现过的字母就是 0,就不会被添加到结果中
  13. minnum=min(a.count(k) for a in A)
  14. res+=minnum*k
  15. return res

总结