-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecodeString.cpp
More file actions
37 lines (36 loc) · 1018 Bytes
/
decodeString.cpp
File metadata and controls
37 lines (36 loc) · 1018 Bytes
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
// Source: https://leetcode.com/problems/decode-string/
// Author: Miao Zhang
// Date: 2021-02-07
class Solution {
public:
string decodeString(string s) {
stack<int> st_num;
stack<string> st_str;
string res = "";
int num = 0;
for (auto &c: s) {
if (isdigit(c)) {
num = 10 * num + c - '0';
} else if (c == '[') {
st_str.push(res);
st_num.push(num);
res = "";
num = 0;
} else if (isalpha(c)) {
res += c;
} else if (c == ']') {
int pre_num = st_num.top();
st_num.pop();
string pre_string = st_str.top();
st_str.pop();
string ress = "";
while (pre_num > 0) {
ress += res;
pre_num--;
}
res = pre_string + ress;
}
}
return res;
}
};