题目链接
题目描述
给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
示例
示例1:
输入:[“bella”,”label”,”roller”] 输出:[“e”,”l”,”l”]
提示
1 <= A.length <= 1001 <= A[i].length <= 100A[i][j]是小写字母思路
哈希表
统计每个字符串里字符出现的频次,然后取每个字符的最小频次即可。题解
class Solution {public:vector<string> commonChars(vector<string>& words) {vector<string> ans;if (0 == words.size()) {return ans;}int minCount[26] = {0};int count[26] = {0};for (int i = 0; i < 26; ++i) {minCount[i] = INT_MAX;}for (string& word : words) {memset(count, 0, 26 * sizeof(int));for (char c : word) {++count[c - 'a'];}for (int i = 0; i < 26; ++i) {minCount[i] = min(minCount[i], count[i]);}}for (int i = 0; i < 26; ++i) {for (int j = 0; j < minCount[i]; ++j) {ans.emplace_back(1, i + 'a');}}return ans;}};
复杂度分析
为字符集大小,本题为26,
为数组大小,
为字符串平均长度。
- 时间复杂度:
- 空间复杂度:
