Simple C++ solution read from end to begin
For each formula, we can read from back to begin, and give the result in one pass.\n\nclass Solution {\npublic:\n    string countOfAtoms(string formula) {\n    
For each formula, we can read from back to begin, and give the result in one pass.\n```\nclass Solution {\npublic:\n    string countOfAtoms(string formula) {\n        if (formula.empty()) return formula;\n\t\t// used to calculate the count of parentheses\n        vector<int> factors{1};\n        int fact = 1;\n\t\t// number of element\n        int num = 0;\n\t\t// element name\n        string element = "";\n\t\t// which digit is this number\n        int digit = 1;\n\t\t// counts\n        map<string, int> cnts;\n        for (int i = formula.size() - 1; i >= 0; --i) {\n\t\t\t// if we see a \')\', we need to calculate the current count of the parentheses\n            if (formula[i] == \')\') {\n\t\t\t// if we don\'t have a numer, then the number is 1\n                if (!num) num = 1;\n                factors.push_back(num);\n                fact *= num;\n                num = 0;\n                digit = 1;\n\t\t\t// \'(\' means we are going out one parentheses, lower the counts\n            } else if (formula[i] == \'(\') {\n                fact /= factors.back();\n                factors.pop_back();\n\t\t\t// if it\'s a number, we can calculate the current number\n            } else if (formula[i] >= \'0\' && formula[i] <= \'9\') {\n                num += (formula[i] - \'0\') * digit;\n                digit *= 10;\n\t\t\t// if it\'s a char, means it\'s part of a element\n            } else if (formula[i] >= \'a\' && formula[i] <= \'z\') {\n                element.push_back(formula[i]);\n\t\t\t// Upper case means we have finished reading an element\n            } else if (formula[i] >= \'A\' && formula[i] <= \'Z\') {\n\t\t\t\t// set num to 1 if there is no number\n                if (!num) num = 1;\n\t\t\t\t// element should be at most 2 chars, num is the current number, fact is the accumulate count of parentheses\n                cnts[string(1, formula[i]) + element] += num * fact;\n\t\t\t\t// ready to record a new element\n                element.clear();\n\t\t\t\t// ready to record a new number\n                num = 0;\n                digit = 1;\n            }\n        }\n        string res = "";\n\t\t// write the result\n        for (auto& p : cnts) res += p.first + ((p.second > 1) ? to_string(p.second) : "");\n        return res;\n    }\n};\n```
[]