LeetCode 1002. 查找共用字符
描述
给你一个字符串数组 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] 由小写英文字母组成
题解
class Solution {
public List<String> commonChars(String[] words) {
if (words.length == 0) {
// 没有单词 返回 空
return new ArrayList<>();
}
// 存储小写字母出现情况
int[] help = new int[26];
// 用于存储结果
List<String> res = new ArrayList<>();
// 第一个单词出现的字母存储到help中
for (int i = 0; i < words[0].length(); i++) {
help[words[0].charAt(i) - 'a'] += 1;
}
// 遍历之后的每一个的单词
for (int i = 1; i < words.length; i++) {
// temp 记录当前单词与help字母同时出现情况
int[] temp = new int[26];
for (int j = 0; j < words[i].length(); j++) {
if( help[words[i].charAt(j) - 'a'] != 0
&& help[words[i].charAt(j)-'a'] > temp[words[i].charAt(j)-'a'] ) {
temp[words[i].charAt(j) - 'a']++;
}
}
// 替换最新的公共字符
help = temp;
}
// 根据存储的公共字符添加到结果中
for(int i=0;i<26;i++){
while ((help[i]--)!=0){
res.add(Character.toString(i+'a'));
}
}
// 返回结果
return res;
}
}