题目转载说明
作者:力扣 (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 题解
class Solution {public List<String> commonChars(String[] words) {// 创建 count 数组用于记录字母出现的最小次数int[] count = new int[26];// 先任意选择一个词,这里选择第一个,把每个字母出现的次数进行统计for (char c : words[0].toCharArray()) {count[c - 'a'] += 1;}for (int i = 1; i < words.length; i++) {// 再创建一个数组,用于统计后面每个词的每个字母出现的次数int[] wordCount = new int[26];// 这个 for 用于统计for (int j = 0; j < words[i].length(); j++) {wordCount[words[i].charAt(j) - 'a'] += 1;}// 核心部分,对比两个数组的相同位置上的数,取相对小的出现的次数for (int k = 0; k < count.length; k++) {count[k] = Math.min(wordCount[k], count[k]);}}// 存结果ArrayList<String> res = new ArrayList<>();/** 把 count 数组便利一边,然后通过 index + 'a' 的方式来得到字符* count[index] 表示的就是该字符出现的次数*/for (int i = 0; i < count.length; i++) {if (count[i] > 0) {for (int j = 0; j < count[i]; j++) {res.add(String.valueOf((char)(i + 'a')));}}}return res;}}
Python 题解
class Solution(object):def commonChars(self, A):res=[]if not A:return res# 先通过 set 去重,得到一组 key;需要明确知道的一点是,结果中出现的字母# 必然要出现在每一个单词中key=set(A[0])# 遍历这组 keyfor k in key:# 通过 a.count 得到每一个 key 在每个词中出现的次数,形成一个 list# 然后在 list 中取最小值即可,没有出现过的字母就是 0,就不会被添加到结果中minnum=min(a.count(k) for a in A)res+=minnum*kreturn res
