from typing import List
from collections import Counter
class Solution:
def commonChars(self, words: List[str]) -> List[str]:
# Start with the letter counts of the first word
common = Counter(words[0])
for word in words[1:]:
# Intersect with the counts from the next word
common &= Counter(word)
# Expand the counts back into a list of characters
result = []
for char, count in common.items():
result.extend([char] * count)
return result
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<string> commonChars(vector<string>& words) {
vector<int> minFreq(26, INT_MAX);
for (const string& word : words) {
vector<int> freq(26, 0);
for (char c : word) {
freq[c - 'a']++;
}
for (int i = 0; i < 26; ++i) {
minFreq[i] = min(minFreq[i], freq[i]);
}
}
vector<string> res;
for (int i = 0; i < 26; ++i) {
for (int j = 0; j < minFreq[i]; ++j) {
res.push_back(string(1, i + 'a'));
}
}
return res;
}
};
import java.util.*;
class Solution {
public List<String> commonChars(String[] words) {
int[] minFreq = new int[26];
Arrays.fill(minFreq, Integer.MAX_VALUE);
for (String word : words) {
int[] freq = new int[26];
for (char c : word.toCharArray()) {
freq[c - 'a']++;
}
for (int i = 0; i < 26; i++) {
minFreq[i] = Math.min(minFreq[i], freq[i]);
}
}
List<String> result = new ArrayList<>();
for (int i = 0; i < 26; i++) {
for (int j = 0; j < minFreq[i]; j++) {
result.add(String.valueOf((char)(i + 'a')));
}
}
return result;
}
}
/**
* @param {string[]} words
* @return {string[]}
*/
var commonChars = function(words) {
let minFreq = new Array(26).fill(Infinity);
for (let word of words) {
let freq = new Array(26).fill(0);
for (let c of word) {
freq[c.charCodeAt(0) - 97]++;
}
for (let i = 0; i < 26; i++) {
minFreq[i] = Math.min(minFreq[i], freq[i]);
}
}
let res = [];
for (let i = 0; i < 26; i++) {
for (let j = 0; j < minFreq[i]; j++) {
res.push(String.fromCharCode(i + 97));
}
}
return res;
};
words
, where each string consists of lowercase English letters, your task is to find all characters that appear in every string (including duplicates). The result should be a list of single-character strings, each representing a character that is common to all words, as many times as it appears in every word. For example, if a character appears 2 times in every word, include it 2 times in the result. The order of the result does not matter.
words = ["bella", "label", "roller"]
: