From a8d01d000d6448ec4bcbc33e1b0d2b144570d317 Mon Sep 17 00:00:00 2001 From: bumpsoo Date: Sun, 14 Jul 2024 21:21:11 +0900 Subject: [PATCH] https://leetcode.com/problems/number-of-atoms --- hard/number_of_atoms.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 hard/number_of_atoms.py diff --git a/hard/number_of_atoms.py b/hard/number_of_atoms.py new file mode 100644 index 0000000..c356744 --- /dev/null +++ b/hard/number_of_atoms.py @@ -0,0 +1,40 @@ +# https://leetcode.com/problems/number-of-atoms +from typing import Dict, List + +class Solution: + def countOfAtoms(self, formula: str) -> str: + s: List[Dict[str, int]] = [{}] + idx = 0 + while idx < len(formula): + if formula[idx] == ')': + idx += 1 + mul = 0 + while idx < len(formula) and formula[idx].isdecimal(): + mul = mul * 10 + int(formula[idx]) + idx += 1 + if mul == 0: + mul = 1 + d = s.pop() + for key in d: + s[-1][key] = s[-1].get(key, 0) + (d[key] * mul) + continue + if formula[idx] == '(': + s.append({}) + idx += 1 + continue + key = '' + if formula[idx].isalpha(): + key += formula[idx] + idx += 1 + while idx < len(formula) and formula[idx].islower(): + key += formula[idx] + idx += 1 + cnt = 0 + while idx < len(formula) and formula[idx].isdecimal(): + cnt = cnt * 10 + int(formula[idx]) + idx += 1 + if cnt == 0: + cnt = 1 + s[-1][key] = s[-1].get(key, 0) + cnt + return ''.join(key + (str(v) if v > 1 else '') for key, v in sorted(s[-1].items())) +