-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
44 lines (32 loc) · 1.16 KB
/
main.py
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
39
40
41
42
43
44
class Solution:
def countOfAtoms(self, formula: str) -> str:
p = 0
def getNumber():
nonlocal p
v = 1
if p < len(formula) and formula[p].isdigit():
v = 0
while p < len(formula) and formula[p].isdigit():
v = v * 10 + int(formula[p])
p += 1
return v
def process():
nonlocal p
freq = defaultdict(int)
while p < len(formula) and formula[p] != ")":
if formula[p] == "(":
p += 1
f = process()
p += 1
num = getNumber()
for k, v in f.items():
freq[k] += v * num
else:
k = formula[p]
p += 1
if p < len(formula) and formula[p].islower():
k = formula[p - 1:p + 1]
p += 1
freq[k] += getNumber()
return freq
return "".join([f"{k}{'' if v == 1 else str(v)}" for k, v in sorted(process().items())])