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
這道題給了一組由小寫字母組成的字符串,讓返回所有的字符串中的相同的字符,重復的字符要出現對應的次數。其實這道題的核心就是如何判斷字符串的相交部分,跟之前的 Intersection of Two Arrays II 和 Intersection of Two Arrays 比較類似。核心是要用 HashMap 建立字符和其出現次數之間的映射,這里由於只有小寫字母,所以可以使用一個大小為 26 的數組來代替 HashMap。用一個數組 cnt 來記錄相同的字母出現的次數,初始化為整型最大值,然后遍歷所有的單詞,對於每個單詞,新建一個大小為 26 的數組t,並統計每個字符出現的次數,然后遍歷0到25各個位置,取 cnt 和 t 對應位置上的較小值來更新 cnt 數組,這樣得到就是在所有單詞里都出現的字母的個數,最后再把這些字符轉為字符串加入到結果 res 中即可,參見代碼如下:
class Solution {
public:
vector<string> commonChars(vector<string>& A) {
vector<string> res;
vector<int> cnt(26, INT_MAX);
for (string word : A) {
vector<int> t(26);
for (char c : word) ++t[c - 'a'];
for (int i = 0; i < 26; ++i) {
cnt[i] = min(cnt[i], t[i]);
}
}
for (int i = 0; i < 26; ++i) {
for (int j = 0; j < cnt[i]; ++j) {
res.push_back(string(1, 'a' + i));
}
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1002
類似題目:
參考資料:
https://leetcode.com/problems/find-common-characters/
https://leetcode.com/problems/find-common-characters/discuss/247573/C%2B%2B-O(n)-or-O(1)-two-vectors