Java solution, Map + Recursion
\nclass Solution {\n    public String countOfAtoms(String formula) {\n        Map<String, Integer> map = countHelper(formula);\n\n        List<String> atoms = n
```\nclass Solution {\n    public String countOfAtoms(String formula) {\n        Map<String, Integer> map = countHelper(formula);\n\n        List<String> atoms = new ArrayList<>(map.keySet());\n        Collections.sort(atoms);\n        StringBuilder sb = new StringBuilder();\n        for (String atom : atoms) {\n            sb.append(atom + (map.get(atom) > 1 ? map.get(atom) : ""));\n        }\n\n        return sb.toString();\n    }\n\n    private Map<String, Integer> countHelper(String formula) {\n        Map<String, Integer> map = new HashMap<>();\n        if (formula.isEmpty()) return map;\n\n        int i = 0;\n        while (i < formula.length()) {\n            if (formula.charAt(i) == '(') {\n                int count = 0, j = i;\n                for (; j < formula.length(); j++) {\n                    if (formula.charAt(j) == '(') count++;\n                    else if (formula.charAt(j) == ')') count--;\n                    if (count == 0) break;\n                }\n                Map<String, Integer> subMap = countHelper(formula.substring(i + 1, j));\n\n                j++;\n                int n = 1, k = j;\n                while (k < formula.length() && Character.isDigit(formula.charAt(k))) k++;\n                if (k > j) {\n                    n = Integer.parseInt(formula.substring(j, k));\n                }\n\n                for (String atom : subMap.keySet()) {\n                    map.put(atom, subMap.get(atom) * n + map.getOrDefault(atom, 0));\n                }\n\n                i = k;\n            } else {\n                int j = i + 1;\n                while (j < formula.length() && formula.charAt(j) >= 'a' && formula.charAt(j) <= 'z') j++;\n\n                int n = 1, k = j;\n                while (k < formula.length() && Character.isDigit(formula.charAt(k))) k++;\n                if (k > j) {\n                    n = Integer.parseInt(formula.substring(j, k));\n                }\n\n                String atom = formula.substring(i, j);\n                map.put(atom, n + map.getOrDefault(atom, 0));\n\n                i = k;\n            }\n        }\n\n        return map;\n    }\n}\n```
[]