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.
Example 1:
Input: words = ["bella","label","roller"] Output: ["e","l","l"]
Example 2:
Input: words = ["cool","lock","cook"] Output: ["c","o"]
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
consists of lowercase English letters.
题目要求找数组里所有string的共同字符(含重复的)。刚开始想的是把第一个当成基准,把第一个的每个字符放到后面的string里找,如果没有就把它remove。看了解答以后才发现有更好的方法,维护一个dictionary,直接求每个字母在一个word中出现的次数的最小值。
class Solution {
public List<String> commonChars(String[] words) {
List<String> result = new ArrayList<>();
int[] all = new int[26];
for (int i = 0; i < 26; i++) {
all[i] = 10000;
}
int[] count = new int[26];
for (String word : words) {
for (char c : word.toCharArray()) {
count[c - 'a']++;
}
for (int i = 0; i < 26; i++) {
all[i] = Math.min(count[i], all[i]);
count[i] = 0; // reset count
}
}
for (int i = 0; i < 26; i++) {
for (int j = 0; j < all[i]; j++) {
result.add(String.valueOf((char)('a' + i)));
}
}
return result;
}
}