代码随想录二刷笔记记录
给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
示例 1:
输入:words = [“bella”,“label”,“roller”]
输出:[“e”,“l”,“l”]
示例 2:
输入:words = [“cool”,“lock”,“cook”]
输出:[“c”,“o”]

a b e l o r z
bella: [1 1 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]
label: [1 1 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]
roller: [0 0 0 0 1 0 0 0 0 0 0 2 0 0 1 0 0 2 0 0 0 0 0 0 0 0 ]
Math.min: [0 0 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]
得到输出["e","l","l"]
完整代码实现
public List<String> commonChars(String[] words) {
List<String> res = new ArrayList<>();
if(words.length == 0) return res;
//扫描第一个String,初始化 hash
int[] record = new int[26]; // 记录第 1 个String的 Hash
for (int i = 0; i < words[0].length();i++){
record[words[0].charAt(i) - 'a']++;
}
//扫描之后的 String
for (int i = 1; i < words.length;i++){
int[] temp = new int[26]; // 记录第 i 个 String 的 Hash
for (int j = 0; j < words[i].length();j++){
temp[words[i].charAt(j) - 'a']++;
}
//对比 第 i 个 String 和第 i-1 个 String 的 Hash
for(int k = 0; k < record.length;k++){
record[k] = Math.min(record[k],temp[k]);取 Hash 最小值
}
}
//转换为 String
for (int i = 0;i < record.length;i++) {
while (record[i] > 0){
//因为有重复,所以需要 while
char c = (char)(i+'a');
res.add(String.valueOf(c));
record[i]--;
}
}
return res;
}