-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
53 lines (49 loc) · 1.29 KB
/
main.cpp
File metadata and controls
53 lines (49 loc) · 1.29 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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
string decodeString(string s)
{
stack<pair<int, string>> pairs; // (multiplier, current_string)
int multiplier = 0;
string current_string = "";
for (char el : s)
{
if (isdigit(el))
multiplier = multiplier * 10 + (el - '0');
else if (el == '[')
{
pairs.push({multiplier, current_string});
multiplier = 0;
current_string = "";
}
else if (el == ']')
{
auto [prev_multiplier, prev_string] = pairs.top();
pairs.pop();
string constructed = "";
for (int i = 0; i < prev_multiplier; ++i)
constructed += current_string;
current_string = prev_string + constructed;
}
else
current_string += el;
}
return current_string;
}
};
int main()
{
string input("3[a2[k]]2[bc1[z]]");
try
{
cout << "input: " << input << endl;
cout << "output: " << Solution().decodeString(input) << endl;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
return 0;
}