原题说明
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:
解题思路
用哈希表ansMap
记录当前可能字符以及其出现次数,也就是把字符作为key
,频率作为value
用哈希表midMap
记录当前字符串的字符以及出现次数,同样把字符作为key
,频率作为value
核心思想:
- 用第一个字符串初始化
ansMap
- 遍历剩余字符串,每次遍历前,先清空
midMap
,再遍历当前字符串,更新midMap
;
将ansMap
中的key
与midMap
做比较:- 如果不在
midMap
中,直接在ansMap
中删除这个key
; - 否则更新
ansMap
中key
对应的value
,取为midMap
和ansMap
中值较小的那个
- 如果不在
- 遍历
ansMap
,确定返回的vector<string>
示例代码 (cpp)
1 | class Solution { |
复杂度分析
时间复杂度: O(n)
空间复杂度: O(1)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!