public String countOfAtoms(String formula) {
if (formula == null || formula.length() == 0) {
Stack<TreeMap<String, Integer>> stack = new Stack<>();
TreeMap<String, Integer> map = new TreeMap<>();
int n = formula.length();
char c = formula.charAt(index);
TreeMap<String, Integer> temp = map;
// Get the number following ')'
while (index < formula.length() && Character.isDigit(formula.charAt(index))) {
count = 10 * count + formula.charAt(index) - '0';
// If there is no number, it is default to 1
count = count == 0 ? 1 : count;
for (String name : temp.keySet()) {
map.put(name, map.getOrDefault(name, 0) + temp.get(name) * count);
StringBuilder name = new StringBuilder();
// Get the first letter (Capital)
name.append(formula.charAt(index));
// If the atom name has lowercase letter, append it to stringbuilder
while (index < n && Character.isLowerCase(formula.charAt(index))) {
name.append(formula.charAt(index));
// Get the number of atoms following the atom
while (index < n && Character.isDigit(formula.charAt(index))) {
count = 10 * count + formula.charAt(index) - '0';
// If there is no number, it is default to 1
count = count == 0 ? 1 : count;
map.put(name.toString(), map.getOrDefault(name.toString(), 0) + count);
StringBuilder res = new StringBuilder();
for (String name : map.keySet()) {
int count = map.get(name);