【LeetCode】1002. 查找常用字符(C++)

1 题目描述

给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
你可以按任意顺序返回答案。

2 示例描述

2.1 示例 1

输入:[“bella”,“label”,“roller”]
输出:[“e”,“l”,“l”]

2.2 示例 2

输入:[“cool”,“lock”,“cook”]
输出:[“c”,“o”]

3 解题提示

1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] 是小写字母

4 源码详解(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;
    }
};

猜你喜欢

转载自blog.csdn.net/Gyangxixi/article/details/114094864
今日推荐