Concise C++ recursive parser
Lots of code posted are kinda long, following is my concise version.\ncpp\nclass Solution {\npublic:\n    string countOfAtoms(string formula) {\n        int pos
Lots of code posted are kinda long, following is my concise version.\n```cpp\nclass Solution {\npublic:\n    string countOfAtoms(string formula) {\n        int pos = 0;\n        map<string, int> count = parser(formula, pos);\n        string res;\n        for (auto entry : count) {\n            res += entry.first + (entry.second == 1 ? "" : to_string(entry.second));\n        }\n        return res;\n    }\n    \n    map<string, int> parser(string& str, int& pos) {\n        map<string, int> res;\n        while (pos < str.size()) {\n            if (str[pos] == '(') {\n                pos++;\n                for (auto entry : parser(str, pos)) res[entry.first] += entry.second;\n            } else if (str[pos] == ')') {\n                int s = ++pos;\n                while (pos < str.size() && isdigit(str[pos])) pos++;\n                int multiple = stoi(str.substr(s, pos - s));\n                for (auto entry : res) res[entry.first] *= multiple;\n                return res;\n            } else if (isupper(str[pos])) {\n                int s = pos++; // s : start index of this element\n                while (pos < str.size() && islower(str[pos])) pos++;\n                string elem = str.substr(s, pos - s);\n                s = pos; // s : start index of (possible) count of this element\n                while (pos < str.size() && isdigit(str[pos])) pos++;\n                string num = str.substr(s, pos - s);\n                res[elem] += num.empty() ? 1 : stoi(num);\n            }\n        }\n        return res;\n    }\n};\n```
[]