forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
number-of-atoms.cpp
40 lines (39 loc) · 1.32 KB
/
number-of-atoms.cpp
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
38
39
40
// Time: O(n)
// Space: O(n)
class Solution {
public:
string countOfAtoms(string formula) {
stack<map<string, int>> stk;
stk.emplace();
int submatches[] = { 1, 2, 3, 4, 5 };
const auto e = regex("([A-Z][a-z]*)(\\d*)|(\\()|(\\))(\\d*)");
for (regex_token_iterator<string::iterator> it(formula.begin(), formula.end(), e, submatches), end;
it != end;) {
const auto& name = (it++)->str();
const auto& m1 = (it++)->str();
const auto& left_open = (it++)->str();
const auto& right_open = (it++)->str();
const auto& m2 = (it++)->str();
if (!name.empty()) {
stk.top()[name] += stoi(!m1.empty() ? m1 : "1");
}
if (!left_open.empty()) {
stk.emplace();
}
if (!right_open.empty()) {
const auto top = move(stk.top()); stk.pop();
for (const auto& kvp: top) {
stk.top()[kvp.first] += kvp.second * stoi(!m2.empty() ? m2 : "1");
}
}
}
string result;
for (const auto& kvp : stk.top()) {
result += kvp.first;
if (kvp.second > 1) {
result += to_string(kvp.second);
}
}
return result;
}
};