-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon_characters.py
More file actions
38 lines (26 loc) · 1.04 KB
/
common_characters.py
File metadata and controls
38 lines (26 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""Description:
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.
"""
from collections import Counter
class Solution:
def commonChars(self, words: list[str]) -> list[str]:
def common(word1:str, word2:str):
counter1 = Counter(word1)
counter2 = Counter(word2)
common_chars = []
for char in word1:
if counter1[char] > 0 and counter2[char] > 0:
common_chars.append(char)
counter1[char] -= 1
counter2[char] -= 1
return common_chars
Common = []
for i in range(len(words)-1):
if i == 0:
Common = common(words[i], words[i+1])
else:
Common = common(Common, common(words[i], words[i+1]))
return Common
sol = Solution()
string = ["bella", "label", "roller"]
print(sol.commonChars(string))