-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecodeStr.cpp
More file actions
54 lines (54 loc) · 1.46 KB
/
decodeStr.cpp
File metadata and controls
54 lines (54 loc) · 1.46 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
class Solution {
public:
inline bool isDigit(char c){
return '0' <= c && c <= '9';
}
string decodeString(string s) {
if (!s.size()) return "";
stack<string> st;
string temp = s.substr(0, 1);
for (int i = 1; i < s.size(); i++) {
char c = s[i];
if (isDigit(c)) {
if (isDigit(s[i - 1])) temp += c;
else {
st.push(temp);
temp = c;
}
}
else if (c == '[') {
st.push(temp);
st.push("[");
temp = "";
}
else if (c == ']'){
string word = "";
if (temp != "") st.push(temp);
temp = "";
while(st.top() != "[") {
temp = st.top() + temp;
st.pop();
}
st.pop();
int times = std::stoi(st.top());
st.pop();
for (int i = 0; i < times; i++) word += temp;
st.push(word);
temp = "";
}
else {
if (s[i - 1] == '[' || s[i - 1] == ']') {
temp = c;
}
else {
temp += c;
}
}
}
while (!st.empty()) {
temp = st.top() + temp;
st.pop();
}
return temp;
}
};