1002. Find common characters (C++)
1 topic description
Given a string array A consisting of only lowercase letters, return a list of all characters (including repeated characters) displayed in each string in the list. For example, if a character appears 3 times in each string, but not 4 times, you need to include the character 3 times in the final answer.
You can return the answers in any order.
2 Example description
2.1 Example 1
Input: ["bella","label","roller"]
Output: ["e","l","l"]
2.2 Example 2
Input: ["cool","lock","cook"]
Output: ["c","o"]
3 Problem solving tips
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] are lowercase letters
4 Detailed source code (C++)
class Solution {
public:
vector<string> commonChars(vector<string>& A) {
int arr[101][26] = {
0 }; //全部初始化为0
vector<string> res ; //返回值
for ( int i = 0 ; i < A.size() ; i ++ )
{
for ( int j = 0 ; j < A[i].size() ; j ++ )
{
arr[i][A[i][j] - 'a'] ++ ; //计算每个字母出现的频率,并存入对应的下标
}
}
for ( int i = 0 ; i < 26 ; i ++ )
{
int maxCount = INT_MAX ;
for ( int j = 0 ; j < A.size() ; j ++ )
{
//分别计算26个字母在每个字符串中出现的频率,取最小的那个
maxCount = min( maxCount , arr[j][i] );
}
char c = i + 'a' ;
char buffer[2] = {
c} ;
while(maxCount--)
{
res.push_back(buffer);
}
}
return res;
}
};