[LeetCode] 1002. Find Common Characters 寻找相同字符
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
这道题给了一组由小写字母组成的字符串,让返回所有的字符串中的相同的字符,重复的字符要出现对应的次数。其实这道题的核心就是如何判断字符串的相交部分,跟之前的 Intersection of Two Arrays II 和 Intersection of Two Arrays 比较类似。核心是要用 HashMap 建立字符和其出现次数之间的映射,这里由于只有小写字母,所以可以使用一个大小为 26 的数组来代替 HashMap。用一个数组 cnt 来记录相同的字母出现的次数,初始化为整型最大值,然后遍历所有的单词,对于每个单词,新建一个大小为 26 的数组t,并统计每个字符出现的次数,然后遍历0到25各个位置,取 cnt 和 t 对应位置上的较小值来更新 cnt 数组,这样得到就是在所有单词里都出现的字母的个数,最后再把这些字符转为字符串加入到结果 res 中即可,参见代码如下:
class Solution {
public:
vector<string> commonChars(vector<string>& A) {
vector<string> res;
vector<int> cnt(26, INT_MAX);
for (string word : A) {
vector<int> t(26);
for (char c : word) ++t[c - 'a'];
for (int i = 0; i < 26; ++i) {
cnt[i] = min(cnt[i], t[i]);
}
}
for (int i = 0; i < 26; ++i) {
for (int j = 0; j < cnt[i]; ++j) {
res.push_back(string(1, 'a' + i));
}
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1002
类似题目:
参考资料:
https://leetcode.com/problems/find-common-characters/
https://leetcode.com/problems/find-common-characters/discuss/247573/C%2B%2B-O(n)-or-O(1)-two-vectors
相关文章
- Leetcode: ZigZag Conversion
- LeetCode高频题3:无重复字符的最长子串
- JS Leetcode 80. 删除有序数组中的重复项 II题解,常规解法与快慢双指针做法
- 【看懂LeetCode】3. 无重复字符的最长子串
- [LeetCode]剑指 Offer 50. 第一个只出现一次的字符
- 每日leetcode算法题:3. 无重复字符的最长子串
- 【LeetCode】46. Permutations (2 solutions)
- 【LeetCode】92. Reverse Linked List II
- 部门工资前三高的所有员工 - LeetCode
- [LeetCode] 1192. Critical Connections in a Network 查找集群内的关键连接
- [LeetCode] 1138. Alphabet Board Path 字母板上的路径
- [LeetCode] 828. Count Unique Characters of All Substrings of a Given String 统计给定字符串的所有子串的独特字符
- [LeetCode] Most Profit Assigning Work 安排最大利润的工作
- [LeetCode] 363. Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K
- [LeetCode] 395. Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串
- [LeetCode] First Unique Character in a String 字符串第一个不同字符
- [LeetCode] 4. Median of Two Sorted Arrays 两个有序数组的中位数