/* * 2021-7-6 00:43:56 * author: etoa */ classSolution { public: int n; stringcountOfAtoms(string formula){ n = formula.size(); int u = 0; auto ordereded_map = dfs(formula, u); string res; for (auto &[atom, cnt] : ordereded_map) { res += atom; if (cnt > 1) res += to_string(cnt); } return res; }
map<string, int> dfs(string &formula, int &u) { map<string, int> tres; for (; u < n;) { if (formula[u] == '(') { ++u; auto tmap = dfs(formula, u); // checks if current is digits int mul = 0, k = u; for (; k < n && isdigit(formula[k]); ++k) { mul = mul * 10 + formula[k] - '0'; } if (!mul) ++mul; u = k; // merge for (auto &[atom, cnt] : tmap) { tres[atom] += cnt * mul; } } elseif (formula[u] == ')') { // endof dfs ++u; break; } else { int k = u + 1; // 从字母的下一位开始 string atom; for (; k < n && islower(formula[k]); ++k); int atomlen = k - u; atom = formula.substr(u, atomlen); //cout << atom << endl; int cnt = 0; for (; k < n && isdigit(formula[k]); k++) { cnt = cnt * 10 + formula[k] - '0'; } if (!cnt) ++cnt; //cout << cnt << endl; tres[atom] += cnt; u = k; } } return tres; } };
classSolution { public: MPSI dfs(string& str, int& u){ MPSI res; while (u < str.size()) { if (str[u] == '(') { u ++ ; auto t = dfs(str, u); u ++ ; int cnt = 1, k = u; while (k < str.size() && isdigit(str[k])) k ++ ; if (k > u) { cnt = stoi(str.substr(u, k - u)); u = k; } for (auto& [x, y]: t) res[x] += y * cnt; } elseif (str[u] == ')') break; else { int k = u + 1; while (k < str.size() && str[k] >= 'a' && str[k] <= 'z') k ++ ; auto key = str.substr(u, k - u); u = k; int cnt = 1; while (k < str.size() && isdigit(str[k])) k ++ ; if (k > u) { cnt = stoi(str.substr(u, k - u)); u = k; } res[key] += cnt; } } return res; }
stringcountOfAtoms(string formula){ int k = 0; auto t = dfs(formula, k); string res; for (auto& [x, y]: t) { res += x; if (y > 1) res += to_string(y); } return res; } };