Keshawn_lu's Blog

Leetcode 1002. 查找常用字符

字数统计: 405阅读时长: 1 min
2020/10/14 Share

题目简介:

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

你可以按任意顺序返回答案。

示例 1:

1
2
输入:["bella","label","roller"]
输出:["e","l","l"]

示例 2:

1
2
输入:["cool","lock","cook"]
输出:["c","o"]

提示:

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

思路:

定义一个数组frequence来存储每个字母出现的最少次数

定义一个数组temp来存储遍历每个字符串过程中字母出现的次数,之后并与frequence进行比较,更新frequence

最后根据frequence的值来返回结果数组。

tip:

  • 需要注意将char转化为string

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
vector<string> commonChars(vector<string>& A) {

vector<string> res;
vector<int> frequence(26, INT_MAX); //存储最少出现次数

for(int i = 0; i < A.size(); i++){

vector<int> temp(26, 0);

for(int j = 0; j < A[i].size(); j++){

temp[A[i][j] - 'a']++;
}

for(int j = 0; j < 26; j++){

if(temp[j] != 0) //存储最小值
frequence[j] = min(frequence[j], temp[j]);
else
frequence[j] = 0;
}
}

for(int i = 0; i < 26; i++){

for(int count = 0; count < frequence[i]; count++){

string s(1, 'a' + i); //char 转化为 string
res.push_back(s);
}
}

return res;
}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: