tags:
- 简单
- 参考
- 数组
flag: yellow
style: summer
date: ‘2019-7-5’
1002.查找常见字符
一、题目
给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
你可以按任意顺序返回答案。
-
示例 1:
输入:[“bella”,“label”,“roller”]
输出:[“e”,“l”,“l”] -
示例 2:
输入:[“cool”,“lock”,“cook”]
输出:[“c”,“o”] -
提示:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] 是小写字母
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-common-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解答
- 解答一:
class Solution {
public List<String> commonChars(String[] A) {
// 入参检查
if(A == null || A.length == 0 || A.length == 1) {
return null;
}
// 记录每个字符出现的次数(字符的ASCII码-97的值做数组下标)
int[] hash = new int[26];
// 是否第一次维护hash数组
boolean firstFlag = true;
// 遍历字符串
for (String word : A) {
// 拆分成字符数组
char[] wordChars = word.toCharArray();
// 如果是第一次维护hash数组
if (firstFlag) {
// 直接记录每个字符出现的个数
for (char wordChar : wordChars) {
hash[wordChar - 97]++;
}
// 标志置为否
firstFlag = false;
// 如果不是第一次维护,即hash数组中有值时
}else {
// 新建临时数组tmpHash来记录当前字符数组每个字符出现的次数
int[] tmpHash = new int[26];
for (char wordChar : wordChars) {
tmpHash[wordChar - 97]++;
}
// 维护hash数组
for(int i = 0; i < hash.length; ++i) {
// 比较hash数组和tmpHash数组
// hash记录每次每个字符出现的最小次数
if(hash[i] > tmpHash[i]) {
hash[i] = tmpHash[i];
}
}
}
}
// 组装返回结果
List<String> res = new ArrayList<>();
for(int i = 0; i < hash.length; ++i) {
if(hash[i] != 0) {
String tmp = String.valueOf((char)(i + 97));
for(int j = 0; j < hash[i]; ++j) {
res.add(tmp);
}
}
}
return res;
}
}
复杂度分析:
执行用时 :3 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗 :37.2 MB, 在所有 Java 提交中击败了94.24%的用户
作者:cafebabe
链接:https://leetcode-cn.com/problems/two-sum/solution/wei-hu-ji-lu-mei-ge-zi-fu-chu-xian-ci-shu-de-shu-z/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
- 解法二:
思路:建立二维映射表,统计每个字符的最小共同出现次数即可。
代码:
class Solution {
public List<String> commonChars(String[] A) {
if (A == null || A.length < 1) {
return null;
}
List<String> ans = new ArrayList<>();
int mapLetter[][] = new int[A.length][26];
for (int i = 0;i < A.length;i++) {
map(A[i],mapLetter[i]);
}
for (int i = 0;i < 26;i++) {
int min = Integer.MAX_VALUE;
for (int j = 0;j < A.length;j++) {
if (min > mapLetter[j][i]) {
min = mapLetter[j][i];
}
}
while (min-- > 0) {
ans.add(String.valueOf((char) (i + 'a')));
}
}
return ans;
}
private void map(String s,int a[]) {
for (int i = 0;i < s.length();i++) {
a[s.charAt(i) - 'a']++;
}
}
}
复杂度分析:
执行用时 :3 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗 :37.8 MB, 在所有 Java 提交中击败了91.94%的用户
作者:zi-mo-10
链接:https://leetcode-cn.com/problems/two-sum/solution/zi-fu-ying-she-tong-ji-zui-xiao-gong-tong-chu-xian/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。