-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path0726-number-of-atoms.py
48 lines (35 loc) · 1.18 KB
/
0726-number-of-atoms.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
45
46
47
48
# time complexity: O(nlogn)
# space complexity: O(n)
from collections import defaultdict
import re
class Solution:
def countOfAtoms(self, formula: str) -> str:
matcher = re.findall(r"([A-Z][a-z]*)(\d*)|(\()|(\))(\d*)", formula)
matcher.reverse()
finalMap = defaultdict(int)
stack = [1]
running_mul = 1
for atom, count, left, right, multiplier in matcher:
if atom:
if count:
finalMap[atom] += int(count) * running_mul
else:
finalMap[atom] += 1 * running_mul
elif right:
if not multiplier:
multiplier = 1
else:
multiplier = int(multiplier)
running_mul *= multiplier
stack.append(multiplier)
elif left:
running_mul //= stack.pop()
finalMap = dict(sorted(finalMap.items()))
ans = ""
for atom in finalMap:
ans += atom
if finalMap[atom] > 1:
ans += str(finalMap[atom])
return ans
formula = "K4(ON(SO3)2)2"
print(Solution().countOfAtoms(formula))