「这是我参与2022首次更文挑战的第18天,活动详情查看:2022首次更文挑战」。
题目描述:
1002. 查找共用字符 - 力扣(LeetCode) (leetcode-cn.com)
给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
示例一
输入: words = ["bella","label","roller"]
输出: ["e","l","l"]
示例二
输入: words = ["cool","lock","cook"]
输出: ["c","o"]
提示:
1 <= words.length <= 1001 <= words[i].length <= 100words[i]由小写英文字母组成
思路分析
哈希表
这题题目有点绕,总结下就是看小写字母在所有单词里有没有都出现,出现的话就输出为答案。
借用代码随想录 大神的一张图
整体思路就是统计出搜索字符串里26个字符的出现的频率,然后取每个字符频率最小值,最后转成输出格式就可以了。
了解了哈希法,就很容易理解该解法了,如果不了解的话可以参考大神的这篇文章。
AC代码
class Solution {
public List<String> commonChars(String[] words) {
List<String> result = new ArrayList<>();
if (words.length == 0) return result;
int[] hash= new int[26]; // 用来统计所有字符串里字符出现的最小频率
for (int i = 0; i < words[0].length(); i++) { // 用第一个字符串给hash初始化
hash[words[0].charAt(i)- 'a']++;
}
// 统计除第一个字符串外字符的出现频率
for (int i = 1; i < words.length; i++) {
int[] hashOtherStr= new int[26];
for (int j = 0; j < words[i].length(); j++) {
hashOtherStr[words[i].charAt(j)- 'a']++;
}
// 更新hash,保证hash里统计26个字符在所有字符串里出现的最小次数
for (int k = 0; k < 26; k++) {
hash[k] = Math.min(hash[k], hashOtherStr[k]);
}
}
// 将hash统计的字符次数,转成输出形式
for (int i = 0; i < 26; i++) {
while (hash[i] != 0) { // 注意这里是while,多个重复的字符
char c= (char) (i+'a');
result.add(String.valueOf(c));
hash[i]--;
}
}
return result;
}
}
总结
不简单的简单题~
参考
查找常用字符 - 查找共用字符 - 力扣(LeetCode) (leetcode-cn.com)
「代码随想录」带你搞定哈希表!1002. 查找常用字符:【哈希法经典应用】详解 - 查找共用字符 - 力扣(LeetCode) (leetcode-cn.com)