Given a string array words, return an array of all characters that show up in all strings within thewords(including duplicates). You may return the answer in any order.
classSolution {
public List<String>commonChars(String[] words) {
int[] commonCharCnt =newint[26];
Arrays.fill(commonCharCnt, Integer.MAX_VALUE);
for (String word: words) {
int[] currCharCnt =newint[26];
word.chars().forEach(character ->++currCharCnt[character -'a']);
for (int i = 0; i < 26; i++) {
commonCharCnt[i]= Math.min(commonCharCnt[i], currCharCnt[i]);
}
}
List<String> commonChars =new ArrayList<>();
for (char character ='a'; character <='z'; character++) {
String currChar = Character.toString(character);
while (commonCharCnt[character -'a']--> 0) {
commonChars.add(currChar);
}
}
return commonChars;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defcommonChars(self, words: list[str]) -> list[str]:
# Initialize commonCharCnt with infinity for all 26 lowercase letters commonCharCnt = [float('inf')] *26for word in words:
currCharCnt = [0] *26for ch in word:
currCharCnt[ord(ch) - ord('a')] +=1for i in range(26):
commonCharCnt[i] = min(commonCharCnt[i], currCharCnt[i])
ans = []
for i in range(26):
ans.extend([chr(i + ord('a'))] * commonCharCnt[i])
return ans