Skip to content

Commit 78754e2

Browse files
Merge pull request #3122 from nkawaller/decode-string
Create: 0394-decode-string.cpp
2 parents 52cdd25 + 789516d commit 78754e2

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

cpp/0394-decode-string.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public:
3+
string decodeString(string s) {
4+
stack<string> stack;
5+
string result;
6+
7+
for (int i = 0; i < s.length(); i++) {
8+
if (s[i] != ']') {
9+
stack.push(string(1, s[i]));
10+
} else {
11+
string substr;
12+
while (!stack.empty() && stack.top() != "[") {
13+
substr = stack.top() + substr;
14+
stack.pop();
15+
}
16+
stack.pop();
17+
18+
string k;
19+
while (!stack.empty() && isdigit(stack.top()[0])) {
20+
k = stack.top() + k;
21+
stack.pop();
22+
}
23+
int kInt = stoi(k);
24+
25+
string temp;
26+
for (int j = 0; j < kInt; j++) {
27+
temp += substr;
28+
}
29+
stack.push(temp);
30+
}
31+
}
32+
33+
while (!stack.empty()) {
34+
result = stack.top() + result;
35+
stack.pop();
36+
}
37+
38+
return result;
39+
}
40+
};

0 commit comments

Comments
 (0)