Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a4713f9

Browse files
committed
1002
1 parent f7ade88 commit a4713f9

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public List<String> commonChars(String[] words) {
3+
HashMap<Character, Integer> ansFre = getFre(words[0]);
4+
for(int i = 1; i < words.length; i++){
5+
HashMap<Character, Integer> curFre = getFre(words[i]);
6+
char c = 'a';
7+
for(Map.Entry<Character, Integer> entrySet : ansFre.entrySet()){
8+
c = entrySet.getKey();
9+
if(curFre.containsKey(c)){
10+
entrySet.setValue(Math.min(entrySet.getValue(), curFre.get(c)));
11+
}else {
12+
entrySet.setValue(0);
13+
}
14+
}
15+
}
16+
List<String> ans = new ArrayList<>();
17+
for(Map.Entry<Character, Integer> entrySet : ansFre.entrySet()){
18+
for(int i = 0; i < entrySet.getValue(); i++){
19+
ans.add(entrySet.getKey()+"");
20+
}
21+
}
22+
return ans;
23+
}
24+
public HashMap<Character, Integer> getFre(String word){
25+
char[] arr = word.toCharArray();
26+
HashMap<Character, Integer> hm = new HashMap<>();
27+
for(char c: arr){
28+
hm.put(c, hm.getOrDefault(c, 0) + 1);
29+
}
30+
return hm;
31+
}
32+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution:
2+
def commonChars(self, words: List[str]) -> List[str]:
3+
def getFre(word):
4+
hm = {}
5+
for c in word:
6+
hm[c] = hm.get(c, 0) + 1
7+
return hm
8+
ansFre = getFre(words[0])
9+
for i in range(1, len(words)):
10+
curFre = getFre(words[i])
11+
for key, value in ansFre.items():
12+
if key in curFre:
13+
ansFre[key] = min(ansFre[key], curFre[key])
14+
else:
15+
ansFre[key] = 0
16+
ans = []
17+
for key, value in ansFre.items():
18+
for i in range(value):
19+
ans.append(key)
20+
return ans

0 commit comments

Comments
 (0)