# 726

Mar 31st, 2021
56
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. class Solution:
2.     def countOfAtoms(self, formula):
3.         dic, coeff, stack, elem, cnt, i = collections.defaultdict(int), 1, [], "", 0, 0
4.         for c in formula[::-1]:
5.             if c.isdigit():
6.                 cnt += int(c) * (10 ** i)
7.                 i += 1
8.             elif c == ")":
9.                 if not cnt: cnt=1;
10.                 stack.append(cnt)
11.                 coeff *= cnt
12.                 i = cnt = 0
13.             elif c == "(":
14.                 coeff //= stack.pop()
15.                 i = cnt = 0
16.             elif c.isupper():
17.                 elem += c
18.                 dic[elem[::-1]] += (cnt or 1) * coeff
19.                 elem = ""
20.                 i = cnt = 0
21.             elif c.islower():
22.                 elem += c
23.         return "".join(k + str(v > 1 and v or "") for k, v in sorted(dic.items()))
RAW Paste Data