-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0394-decode-string.cpp
40 lines (35 loc) · 1.02 KB
/
0394-decode-string.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
class Solution {
public:
string decodeString(string s) {
stack<string> stack;
string result;
for (int i = 0; i < s.length(); i++) {
if (s[i] != ']') {
stack.push(string(1, s[i]));
} else {
string substr;
while (!stack.empty() && stack.top() != "[") {
substr = stack.top() + substr;
stack.pop();
}
stack.pop();
string k;
while (!stack.empty() && isdigit(stack.top()[0])) {
k = stack.top() + k;
stack.pop();
}
int kInt = stoi(k);
string temp;
for (int j = 0; j < kInt; j++) {
temp += substr;
}
stack.push(temp);
}
}
while (!stack.empty()) {
result = stack.top() + result;
stack.pop();
}
return result;
}
};