1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Solution { public: map<string, int> dfs(const string &formula, int &curr) { map<string, int> ans; while (curr < formula.size() && formula[curr] != ')') { if (formula[curr] == '(') { ++curr; auto tmp = dfs(formula, curr); int next = curr; while (next < formula.size() && isdigit(formula[next])) ++next; int num = curr == next ? 1 : stoi(formula.substr(curr, next - curr)); curr = next; for (auto &[atom, v] : tmp) ans[atom] += num * v; } else { int next = curr + 1; while (next < formula.size() && islower(formula[next])) ++next; string atom = formula.substr(curr, next - curr); curr = next; while (next < formula.size() && isdigit(formula[next])) ++next; int num = curr == next ? 1 : stoi(formula.substr(curr, next - curr)); ans[atom] += num; curr = next; } } ++curr; return ans; } string countOfAtoms(string formula) { int curr = 0; auto atomNum = dfs(formula, curr); string ans; for (auto &[atom, num] : atomNum) ans += (num == 1 ? atom : atom + to_string(num)); return ans; } };
|