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
这题是找给出的字符串数组的相同的字符。我这里偷懒,直接硬解。找出每个字符串字符出现的次数,然后在别的字符串里找,找到的最小的就是我们要的结果。
class FindCommonCharacters : public Solution {
public:
void Execute() {
auto res = commonChars(vector<string> {"cool"});
}
vector<string> commonChars(const vector<string> &A) {
vector<map<char, int>> counters;
for (auto &line : A) {
map<char, int> counter;
for (auto c : line) {
auto it = counter.find(c);
if (it == counter.end()) {
counter.insert(std::make_pair(c, 1));
} else {
it->second++;
}
}
counters.push_back(std::move(counter));
}
// Loop maps
vector<string> res;
if (counters.size() == 1) {
// Split the word
for (auto c : A[0]) {
char ch[2];
ch[0] = c;
ch[1] = '\0';
res.push_back(std::string(ch));
}
return res;
}
for (int i = 1; i < counters.size(); i++) {
for (auto &pa : counters[0]) {
auto it = counters[i].find(pa.first);
if (it == counters[i].end()) {
// Not found in other string
pa.second = 0;
} else {
// Select the min one
pa.second = pa.second < it->second ? pa.second : it->second;
}
}
}
for (auto &pa : counters[0]) {
for (int i = 0; i < pa.second; i++) {
char ch[2];
ch[0] = pa.first;
ch[1] = 0;
res.push_back(std::string(ch));
}
}
return res;
}
};