-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathLeetCode_726_41.cpp
More file actions
84 lines (80 loc) · 2.02 KB
/
LeetCode_726_41.cpp
File metadata and controls
84 lines (80 loc) · 2.02 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* @lc app=leetcode id=726 lang=cpp
*
* [726] Number of Atoms
* T(n) = O(N)
* S(n) = O(N)
*/
class Solution
{
public:
string countOfAtoms(string f)
{
stack<map<string, int>> st;
map<string, int> cur;
int i = 0;
while (i < f.size())
{
if (f[i] == '(')
{
processLeftBracket(cur, st, i);
}
else if (f[i] == ')')
{
processRightBracket(i, f, cur, st);
}
else
{
processCount(i, f, cur);
}
}
string ans;
for (auto p : cur)
{
ans += p.first;
if (p.second > 1)
ans += to_string(p.second);
}
return ans;
}
private:
void processLeftBracket(map<string, int> &cur,
stack<map<string, int>> &st,
int &i)
{
st.push(move(cur));
cur = map<string, int>();
++i;
}
void processRightBracket(int &i,
string f,
map<string, int> &cur,
stack<map<string, int>> &st)
{
int j = i + 1;
int num = 0;
while (j < f.size() && isdigit(f[j]))
num = num * 10 + (f[j++] - '0');
num = max(num, 1);
for (auto p : cur)
st.top()[p.first] += p.second * num;
cur = move(st.top());
st.pop();
i = j;
}
void processCount(int &i,
string f,
map<string, int> &cur)
{
int j = i + 1;
int num = 0;
while (j < f.size() && f[j] >= 'a' && f[j] <= 'z')
++j;
auto name = f.substr(i, j - i);
while (j < f.size() && isdigit(f[j]))
num = num * 10 + (f[j++] - '0');
num = max(num, 1);
cur[name] += num;
i = j;
}
};