| 考点 | 难度 |
|---|---|
| Hash Table | Easy |
Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.
思路需要两个helper function:
1 计算每个string里面出现的字母次数
2 求两个string里面字母的交集(取两个次数之间小的)
最后把每个次数大于0的字母按剩余次数加到array中返回。
class Solution {
public List commonChars(String[] words) {
int[] last = count(words[0]);
for (int i = 1; i < words.length; i++) {
last = intersection(last, count(words[i]));
}
List arr = new ArrayList<>();
for (int i = 0; i < 26; i++) {
if (last[i] != 0) {
char a = 'a';
a += i;
String s = String.valueOf(a);
while (last[i] > 0) {
arr.add(s);
last[i]--;
}
}
}
return arr;
}
int[] intersection(int[] a, int[] b) {
int[] t = new int[26];
for (int i = 0; i < 26; i++) {
t[i] = Math.min(a[i], b[i]);
}
return t;
}
int[] count(String str) {
int[] t = new int[26];
for (char c : str.toCharArray()) t[c - 'a']++;
return t;
}
}



