java o(n) stack solution, love u all
\nimport java.util.*;\n\nclass Solution {\n    private String getToken(String formula, int pos) {\n        if (Character.isLetter(formula.charAt(pos))) {\n     
```\nimport java.util.*;\n\nclass Solution {\n    private String getToken(String formula, int pos) {\n        if (Character.isLetter(formula.charAt(pos))) {\n            int i = pos;\n            while (i >= 0 && Character.isLowerCase(formula.charAt(i))) {\n                --i;\n            }\n            return formula.substring(i, pos + 1);\n        }\n\n        if (Character.isDigit(formula.charAt(pos))) {\n            int i = pos;\n            while (i >= 0 && Character.isDigit(formula.charAt(i))) {\n                --i;\n            }\n            return formula.substring(i + 1, pos + 1);\n        }\n\n        return formula.substring(pos, pos + 1);\n    }\n\n    boolean isNum(String token) {\n        return Character.isDigit(token.charAt(0));\n    }\n\n    boolean isAtom(String token) {\n        return Character.isLetter(token.charAt(0));\n    }\n\n    public String countOfAtoms(String formula) {\n        Map<String, Integer> atoms = new TreeMap<>();\n\n        int mul = 1;\n        Stack<Integer> stk = new Stack<>();\n        int pos = formula.length() - 1;\n        while (pos >= 0) {\n            String token = getToken(formula, pos);\n            pos -= token.length();\n\n            if (isAtom(token)) {\n                atoms.put(token, atoms.getOrDefault(token, 0) + mul);\n            } else if (isNum(token)) {\n                int num = Integer.valueOf(token);\n                String next = getToken(formula, pos);\n                pos -= next.length();\n\n                if (isAtom(next)) {\n                    atoms.put(next, atoms.getOrDefault(next, 0) + num * mul);\n                } else {\n                    mul *= num;\n                    stk.push(num);\n                }\n            } else if (token.equals(")")) {\n                stk.push(1);\n            } else {\n                mul /= stk.peek();\n                stk.pop();\n            }\n        }\n\n        StringBuilder res = new StringBuilder();\n        for (Map.Entry<String, Integer> e : atoms.entrySet()) {\n            res.append(e.getKey());\n            if (e.getValue() != 1) {\n                res.append(e.getValue());\n            }\n        }\n        return res.toString();\n    }\n}\n```
[]