Given an array A
of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
Example 1:
Input: ["bella","label","roller"] Output: ["e","l","l"]
Example 2:
Input: ["cool","lock","cook"] Output: ["c","o"]
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j]
is a lowercase letter
Approach #1 dictionary
class Solution {
public List<String> commonChars(String[] A) {
List<String> ans = new ArrayList<>();
// Common characters dictionary
int[] dict = new int[26];
for (int j = 0; j < A[0].length(); j++) {
dict[A[0].charAt(j) - 'a']++;
}
for (int i = 1; i < A.length; i++) {
// Dictionary of the current word
int[] curr = new int[26];
for (int j = 0; j < A[i].length(); j++) {
curr[A[i].charAt(j) - 'a']++;
}
// Update the common dictionary
for (int j = 0; j < 26; j++) {
if (curr[j] < dict[j])
dict[j] = curr[j];
}
}
for (int i = 0; i < 26; i++) {
for (int j = 0; j < dict[i]; j++) {
ans.add(Character.toString((char) ('a' + i)));
}
}
return ans;
}
}
先把所有String []A 里出现过的字母加到公共字典里,然后对String[] A里每一个String word, 用一个字典储存其每个字母出现过的次数,然后更新公共的字典。
这样一来,公共字典里储存的,都是每个word里字母至少出现的次数,如果没在其他word出现过,会被设为0.
Time: O(n), where n
is the total number of characters in A;
extra space: O(1), excludes output/return space.
Approach #2 与上一方法思想类似,代码更简洁
public List<String> commonChars(String[] A) {
List<String> ans = new ArrayList<>();
int[] count = new int[26];
Arrays.fill(count, Integer.MAX_VALUE);
for (String str : A) {
int[] cnt = new int[26];
for (int i = 0; i < str.length(); ++i) { ++cnt[str.charAt(i) - 'a']; } // count each char's frequency in string str.
for (int i = 0; i < 26; ++i) { count[i] = Math.min(cnt[i], count[i]); } // update minimum frequency.
}
for (char c = 'a'; c <= 'z'; ++c) {
while (count[c - 'a']-- > 0) { ans.add("" + c); }
}
return ans;
}
Time: O(n), where n
is the total number of characters in A;
extra space: O(1), excludes output/return space.
Q: What does ++cnt[c - 'a'];
mean?
A:count the frequency of chars in String str.
c : cnt[c - 'a']
'a': cnt['a' - 'a'] = cnt[0]
'b': cnt['b' - 'a'] = cnt[1]
'c': cnt['c' - 'a'] = cnt[2]
...
'z': cnt['z' - 'a'] = cnt[25]
if char c
represents 'x'
, then cnt[c - 'a'] = cnt[23]
. That is, when encountering char 'x', we increase cnt[23] by 1.
Therefore, after traversal of all chars in String str
, we have the frequency (number of occurrence) of each char in cnt
.