File tree 1 file changed +52
-0
lines changed
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+
3
+ class Solution {
4
+ public:
5
+ string countOfAtoms(string formula) {
6
+ stack<map<string, int>> stk;
7
+ stk.push(map<string, int>());
8
+ int n = formula.size();
9
+ for (int i = 0; i < n;) {
10
+ if (formula[i] == '(') {
11
+ stk.push(map<string, int>());
12
+ i++;
13
+ } else if (formula[i] == ')') {
14
+ auto top = stk.top();
15
+ stk.pop();
16
+ i++;
17
+ int i_start = i;
18
+ while (i < n && isdigit(formula[i])) {
19
+ i++;
20
+ }
21
+ int multiplier = i > i_start ? stoi(formula.substr(i_start, i - i_start)) : 1;
22
+ for (auto &p : top) {
23
+ stk.top()[p.first] += p.second * multiplier;
24
+ }
25
+ } else {
26
+ int i_start = i;
27
+ i++;
28
+ while (i < n && islower(formula[i])) {
29
+ i++;
30
+ }
31
+ string element = formula.substr(i_start, i - i_start);
32
+ i_start = i;
33
+ while (i < n && isdigit(formula[i])) {
34
+ i++;
35
+ }
36
+ int count = i > i_start ? stoi(formula.substr(i_start, i - i_start)) : 1;
37
+ stk.top()[element] += count;
38
+ }
39
+ }
40
+ auto &counts = stk.top();
41
+ vector<pair<string, int>> elements(counts.begin(), counts.end());
42
+ sort(elements.begin(), elements.end());
43
+ string result;
44
+ for (auto &p : elements) {
45
+ result += p.first;
46
+ if (p.second > 1) {
47
+ result += to_string(p.second);
48
+ }
49
+ }
50
+ return result;
51
+ }
52
+ };
You can’t perform that action at this time.
0 commit comments