[LeetCode] Find Common Characters

1002. Find Common Characters

Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<string> commonChars(vector<string>& words) {
vector<int> freq(26,words.size());
for(auto& w : words) {
vector<int> now(26);
for(auto& ch : w) now[ch-'a']++;
for(int i = 0; i < 26; i++) freq[i] = min(freq[i], now[i]);
}
vector<string> res;
for(int i = 0; i < 26; i++) {
for(int j = 0; j < freq[i]; j++) {
res.push_back(string(1,'a' + i));
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/06/05/PS/LeetCode/find-common-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.