C++ AC Solution (Map)
\nclass Solution {\npublic:\n    string countOfAtoms(string formula) {\n        int i = 0;\n        map<string, int> cnt = parseElement(formula, i);\n        st
```\nclass Solution {\npublic:\n    string countOfAtoms(string formula) {\n        int i = 0;\n        map<string, int> cnt = parseElement(formula, i);\n        string res;\n        for (auto const &p : cnt) \n            res += p.first + (p.second > 1 ? to_string(p.second) : "");\n        \n        return res;\n    }\n    \n    map<string, int> parseElement(string &formula, int &i) {\n        map<string, int> cnt;\n        while (i < formula.size() && formula[i] != ')') {\n            if (formula[i] == '(') {\n                auto m = parseElement(formula, ++i);\n                for (auto const &p : m) cnt[p.first] += p.second;\n            }\n            else {\n                string atom;\n                atom += formula[i++];\n                while (i < formula.size() && isalpha(formula[i]) && islower(formula[i]))\n                    atom += formula[i++];\n                cnt[atom] += parseInt(formula, i);\n            }\n        }\n        if (i < formula.size() && formula[i] == ')') {\n            int n = parseInt(formula, ++i);\n            for (auto &p : cnt) p.second *= n;\n        }\n        return cnt;\n    }\n    \n    int parseInt(string& s, int &i) {\n        int n = 0;\n        while (i < s.length() && isdigit(s[i]))\n            n = 10 * n + s[i++] - '0';\n        return n == 0 ? 1 : n;\n    }\n};\n```
[]