-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathDecode_String.cpp
57 lines (56 loc) · 1.75 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {
template<typename T> T toInt(string s) { T n = 0; istringstream sin(s); sin >> n; return n; }
public:
string decodeString(string s) {
string decodedStr = "";
stack<string> Stack;
for(int i = 0, n = s.length(); i < n; ++i) {
if(s[i] == '[') {
// string key = "";
// key += s[i];
// Stack.push(key);
}
else if(isdigit(s[i])) {
string k = "";
k += s[i];
while(i + 1 < n and isdigit(s[i + 1])) {
k += s[i + 1];
++i;
}
Stack.push(k);
}
else if(s[i] == ']') {
string key = "";
while(!Stack.empty()) {
if(isdigit(Stack.top()[0])) break;
key = Stack.top() + key;
Stack.pop();
}
// assert(Stack.top() == "[");
// Stack.pop();
int k = toInt<int>(Stack.top());
Stack.pop();
string newKey = "";
newKey.reserve(key.length() * k);
while(k--) {
newKey += key;
}
Stack.push(newKey);
}
else {
string key = "";
key += s[i];
while(i + 1 < n and s[i + 1] != ']' and !isdigit(s[i + 1])) {
key += s[i + 1];
++i;
}
Stack.push(key);
}
}
while(!Stack.empty()) {
decodedStr = Stack.top() + decodedStr;
Stack.pop();
}
return decodedStr;
}
};