Skip to content

Instantly share code, notes, and snippets.

@CalK16
Created December 26, 2023 23:38
Show Gist options
  • Save CalK16/9176322e7133586eb5480b2f387a4d86 to your computer and use it in GitHub Desktop.
Save CalK16/9176322e7133586eb5480b2f387a4d86 to your computer and use it in GitHub Desktop.
Among the solutions on the web, this is the most simple yet delightful code for solving leetcode 726-number-of-atoms I've ever seen.
class Solution:
def countOfAtoms(self, formula: str) -> str:
i = 0
ans = ""
def _countOfAtoms(formula):
nonlocal i
counts = defaultdict(int)
while i < len(formula):
if formula[i] == "(":
i += 1
tmp_counts = _countOfAtoms(formula)
count = getCount(formula)
for k, v in tmp_counts.items():
counts[k] += v * count
elif formula[i] == ")":
i += 1
return counts
else:
name = getName(formula)
counts[name] += getCount(formula)
return counts
def getName(formula):
nonlocal i
name = ""
while i < len(formula) and formula[i].isalpha() and (not name or formula[i].islower()):
name += formula[i]
i += 1
return name
def getCount(formula):
nonlocal i
count_str = ""
while i < len(formula) and formula[i].isdigit():
count_str += formula[i]
i += 1
return 1 if len(count_str) == 0 else int(count_str)
return "".join(k if v == 1 else (k + str(v)) for k, v in sorted(_countOfAtoms(formula).items()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment