-
Notifications
You must be signed in to change notification settings - Fork 110
/
394-decode-string.cpp
31 lines (30 loc) · 1 KB
/
394-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
#include <stack>
class Solution {
public:
string decodeString(string s) {
stack<string> decodedStack;
stack<int> numStack;
decodedStack.push("");
int numBegin = -1;
for (int i = 0; i < s.size(); i++) {
if (isdigit(s[i]) && numBegin == -1) {
numBegin = i;
} else if (s[i] == '[') {
numStack.push(stoi(s.substr(numBegin, i - numBegin)));
numBegin = -1;
decodedStack.push("");
} else if (s[i] == ']') {
string decodedString;
for (int j = 0; j < numStack.top(); j++) {
decodedString += decodedStack.top();
}
decodedStack.pop();
numStack.pop();
decodedStack.top() += decodedString;
} else if (numBegin == -1) {
decodedStack.top() += s[i];
}
}
return decodedStack.top();
}
};