原題
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
分析
題目的要求很簡單,找出字符串集合中共有的字符,再者數據規模並不大,最多隻有100個字符串,每個字符串裏最多隻有100個字符,因此解決這個問題的關鍵在於找一個合理的數據結構,用來存儲這些公共的字符。
拍腦門解法
由於結果最多可以只有26字符,因此可以長度爲26的數組來記錄‘a’-'z’出現的次數,具體思路如下:
- 初始化count[26] = max_value;用來記錄字符出現的次數
- 遍歷A中的字符串
- 初始化num[26] = 0
- 對於每個字符串,用num數組記錄該字符串中每個字符出現的次數,
- 更新count數組值,count[i] = min(count[i], num[i]),這裏得到的是到當前字符串位置,出現的每個字符的最小次數
- 遍歷count數組
- 如果count[i]>0,表示該字符爲共有字符,且count[i]的值爲出現的次數
作者@perfectpan
class Solution {
public:
int cnt[26],num[26];
vector<string> commonChars(vector<string>& A) {
int i;
for (i=0;i<26;++i) cnt[i]=100000;
for (auto s:A){
for (i=0;i<26;++i) num[i]=0;
for (int i=0;i<(int)s.length();++i){
num[s[i]-'a']++;
}
for (i=0;i<26;++i) cnt[i]=min(cnt[i],num[i]);
}
vector<string> vec;
for (i=0;i<26;++i)if(cnt[i]>0){
string s="";
char ch='a'+i;
s=s+ch;
for (int j=0;j<cnt[i];++j){
vec.push_back(s);
}
}
return vec;
}
};
Python四行解法
這裏要提的一點是,在刷題的過程中,思路固然重要,但是合理的使用語言自身帶有的數據結構庫更重要(更何況一些題本來就用不着什麼思路),有了這些我們便不用去費勁的造輪子,省時省力,可以節約時間來刷更多的題。
下面的解法用到了collections中的Counter類(其更多的用法可以參考博客http://www.pythoner.com/205.html)
這裏只說下用到的兩個知識點:
- Counter(str)得到str中的字符以及字符個數
>>> str = 'cool'
>>> c = Counter(str)
>>> c
Counter({'o': 2, 'c': 1, 'l': 1})
- 兩個Counter之間可以使用&運算符,表示交集,並且計數取最小值(這不正是題目要求的麼?)
>>> Counter('cool') & Counter('lock')
Counter({'c': 1, 'o': 1, 'l': 1})
作者@Hexadecimal
class Solution(object):
def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
c = collections.Counter(A[0])
for i in range(1, len(A)):
c &= collections.Counter(A[i])
return list(c.elements())