2024-06-05 Daily Challenge

Today I have done leetcode's June LeetCoding Challenge with cpp.

June LeetCoding Challenge 5

Description

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.

 

Example 1:

Input: words = ["bella","label","roller"]
Output: ["e","l","l"]

Example 2:

Input: words = ["cool","lock","cook"]
Output: ["c","o"]

 

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists of lowercase English letters.

Solution

class Solution {
public:
  vector<string> commonChars(vector<string>& words) {
    map<char, int> answerCount;
    for(int i = 'a'; i <= 'z'; ++i) answerCount[i] = 100;
    for(const auto &word : words) {
      map<char, int> result;
      for(auto c : word) result[c] += 1;
      for(int i = 'a'; i <= 'z'; ++i) {
        answerCount[i] = min(answerCount[i], result[i]);
      }
    }
    vector<string> answer;
    for(auto [c, times] : answerCount) {
      for(int i = 0; i < times; ++i) {
        answer.push_back(string(1, c)) ;
      }
    }
    return answer;
  }
};