forked from rishigupta1109/ContestsSolutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecodeString.cpp
More file actions
99 lines (81 loc) · 1.81 KB
/
DecodeString.cpp
File metadata and controls
99 lines (81 loc) · 1.81 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include<bits/stdc++.h>
using namespace std;
// Returns decoded string for 'str'
string decode(string str)
{
stack<int> integerstack;
stack<char> stringstack;
string temp = "", result = "";
// Traversing the string
for (int i = 0; i < str.length(); i++)
{
int count = 0;
// If number, convert it into number
// and push it into integerstack.
if (str[i] >= '0' && str[i] <='9')
{
while (str[i] >= '0' && str[i] <= '9')
{
count = count * 10 + str[i] - '0';
i++;
}
i--;
integerstack.push(count);
}
// If closing bracket ']', pop element until
// '[' opening bracket is not found in the
// character stack.
else if (str[i] == ']')
{
temp = "";
count = 0;
if (! integerstack.empty())
{
count = integerstack.top();
integerstack.pop();
}
while (! stringstack.empty() && stringstack.top()!='[' )
{
temp = stringstack.top() + temp;
stringstack.pop();
}
if (! stringstack.empty() && stringstack.top() == '[')
stringstack.pop();
// Repeating the popped string 'temo' count
// number of times.
for (int j = 0; j < count; j++)
result = result + temp;
// Push it in the character stack.
for (int j = 0; j < result.length(); j++)
stringstack.push(result[j]);
result = "";
}
// If '[' opening bracket, push it into character stack.
else if (str[i] == '[')
{
if (str[i-1] >= '0' && str[i-1] <= '9')
stringstack.push(str[i]);
else
{
stringstack.push(str[i]);
integerstack.push(1);
}
}
else
stringstack.push(str[i]);
}
// Pop all the element, make a string and return.
while (! stringstack.empty())
{
result = stringstack.top() + result;
stringstack.pop();
}
return result;
}
// Driven Program
int main()
{
string str = "3[b2[ca]]";
cout << decode(str) << endl;
return 0;
}