# Leetcode 726. Number of Atoms

## 2. Solution

• Version 1
```class Solution:
def countOfAtoms(self, formula):
stat = {}
stack = []
parts = []

# Split string by alpha, number, '(', ')'
for index, ch in enumerate(formula):
if ch.isupper():
parts.append(ch)
elif ch.islower():
parts[-1] += ch
elif ch.isdigit():
if formula[index - 1].isdigit():
parts[-1] += ch
else:
parts.append(ch)
else:
parts.append(ch)

# Calculate the number of atom and remove '(', ')'
stack = []
for index, part in enumerate(parts):
if part.isalpha():
if index + 1 == len(parts) or not parts[index + 1].isdigit():
stack.append(part)
stack.append(1)
else:
stack.append(part)
elif part.isdigit() and parts[index - 1] != ')':
stack.append(int(part))
elif part == '(':
stack.append(part)
elif part == ')':
if index + 1 < len(parts) and parts[index + 1].isdigit():
multiplier = int(parts[index + 1])
else:
multiplier = 1

i = len(stack) - 1
while stack[i] != '(':
if isinstance(stack[i], int):
stack[i] = stack[i] * multiplier
i -= 1
stack.pop(i)

# Stat the number of atoms
for i in range(0, len(stack), 2):
if stack[i] in stat:
stat[stack[i]] += stack[i + 1]
else:
stat[stack[i]] = stack[i + 1]
stat = sorted(stat.items(), key=lambda item: item[0])
result = ''
for key, value in stat:
if value > 1:
result = result + key + str(value)
else:
result = result + key
return result```

## Reference

1. https://leetcode.com/problems/number-of-atoms/

0 条评论

• ### LWC 58：726. Number of Atoms

LWC 58：726. Number of Atoms 传送门：726. Number of Atoms Problem: Given a chemical ...

• ### DOCK-4-生成 Grid

围绕活性位点创建一个box 使用指令：showbox < box.in box.in的文件格式为：

系列文章（点击即可查看） 机器学习该如何应用到量化投资系列（一） 机器学习该如何应用到量化投资系列（二） 机器学习该如何应用到量化投资系列（三） 机器学习该如...

• ### Julia-BioStructures

BioStructures提供了读取，写入和操纵大分子结构（蛋白质）的功能。可以将Protein Data Bank（PDB），mmCIF和MMTF格式的文件读...

• ### LeetCode <BT> 200. Number of Islands

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands...

• ### Leetcode 200. Number of Islands

版权声明：博客文章都是作者辛苦整理的，转载请注明出处，谢谢！ https://blog.cs...

• ### Leetcode 233. Number of Digit One

Given an integer n, count the total number of digit 1 appearing in all non-nega...

• ### Leetcode 191 Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1' b...

• ### LeetCode 191. Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of '1' bi...