I thought of using reverse too, below is my solution (longer but I think more explicit):

class Solution { public: string countOfAtoms(string formula) { stack<map<string, int>> mpSt; stack<int> intSt; map<string, int> curr; string element = ""; int factor = 1, n = formula.size(); reverse(formula.begin(), formula.end()); for (int i = 0; i < n; i++) { char c = formula[i]; if (isdigit(c)) { string factorStr = ""; while (i < n && isdigit(formula[i])) { factorStr += formula[i++]; } reverse(factorStr.begin(), factorStr.end()); factor = stoi(factorStr); i--; } else if (c == ')') { mpSt.push(curr); intSt.push(factor); curr.clear(); factor = 1; element = ""; } else if (c == '(') { curr = mergeDict(mpSt.top(), curr, intSt.top()); mpSt.pop(); intSt.pop(); } else if (isupper(c)) { element = c + element; curr[element] += factor; element = ""; factor = 1; } else element += c; } string res = ""; for (auto it = curr.begin(); it != curr.end(); it++) { res += it -> first + (it -> second == 1 ? "" : to_string(it -> second)); } return res; } map<string, int> mergeDict(map<string, int> prev, map<string, int> curr, int n) { for (auto it = curr.begin(); it != curr.end(); it++) { prev[it -> first] += (it -> second) * n; } return prev; }; };