来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-common-characters
给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按任意顺序 返回答案。
示例 1:输入:words = [“bella”,“label”,“roller”] 输出:[“e”,“l”,“l”]
示例 2:输入:words = [“cool”,“lock”,“cook”] 输出:[“c”,“o”]
提示:1 <= words.length <= 100 1 <= words[i].length <= 100 words[i]
由小写英文字母组成
参考文章:给你一些字符串,查找常用字符
思路:
观察题面,发现“小写字符”、“出现频率”这些关键字,就要联系到使用哈希表来做这道题。
这道题仍然是属于比较简单的哈希表题目,直接使用数组做哈希表即可。统计出每个字符串中每个字符出现的频率,然后更新这些字符在字符串中出现最小的频率(也就是算出每个字符在所有字符串里出现的最小次数)。最后再依据这些频率输出答案即可。
本题Java代码:
class Solution {
public List<String> commonChars(String[] words) {
int[] hash = new int[26];
for (char c : words[0].toCharArray()) {
hash[c - 'a']++;
}
for (int i = 1; i < words.length; i++) {
int[] hashOther = new int[26];
for (char c : words[i].toCharArray()) {
hashOther[c - 'a']++;
}
for (int j = 0; j < 26; j++) {
hash[j] = Math.min(hash[j], hashOther[j]);
}
}
List<String> ans = new ArrayList<>();
for (int i = 0; i < 26; i++) {
char tmp = (char) (i + 'a');
for (int j = 1; j <= hash[i]; j++) {
ans.add(String.valueOf(tmp));
}
}
return ans;
}
}