Repository navigation
Expand file tree
/
Copy pathDecodeString.cpp
More file actions
116 lines (95 loc) · 3.19 KB
/
Copy pathDecodeString.cpp
File metadata and controls
116 lines (95 loc) · 3.19 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// solution complexuty k1[k2[k3[. . . .]]]
// k1*k2 *k3 *k4
// solution 1
class Solution {
public:
string decodeString(string s) {
stack<char> st;
for(auto xt : s)
{
if(xt==']')
{
string ss = "";
while(!st.empty() and st.top()!='[')
{
ss = st.top()+ss;
st.pop();
}
st.pop();
int count = 0 ;
int base = 1;
while(!st.empty() and isdigit(st.top()))
{
count = count + (st.top()-'0')*base;
base = base*10;
st.pop();
}
while(count--)
{
for(auto xr : ss)
st.push(xr);
}
}
else
{
st.push(xt);
}
}
string ans = "";
while(!st.empty())
{
ans = st.top()+ans;
st.pop();
}
return ans;
}
};
// solution 2
class Solution {
public:
string decodeString(string s) {
stack<int>countStack;
stack<string>stringStack;
string curr = "";
int k = 0;
for(auto xt : s)
{
if(isdigit(xt))
{
k = k *10 + (xt-'0');
}
else if(xt=='[')
{
stringStack.push(curr);
countStack.push(k);
k=0;
curr = "";
}
else if(xt==']')
{
string decoded = stringStack.top();stringStack.pop();
int times = countStack.top(); countStack.pop();
while(times--)
{
decoded += curr;
}
curr = decoded;
}
else
{
curr += xt;
}
}
return curr;
}
};
/*
Iterate over the string s and process each character as follows:
Case 1) If the current character is a digit (0-9), append it to the number k.
Case 2) If the current character is a letter (a-z), append it to the currentString.
Case 3) If current character is a opening bracket [, push k and currentString intocountStack and stringStack respectively.
Case 4) Closing bracket ]: We must begin the decoding process,
We must decode the currentString. Pop currentK from the countStack and decode the pattern currentK[currentString]
As the stringStack contains the previously decoded string, pop the decodedString from the stringStack. Update the decodedString = decodedString + currentK[currentString]
Time Complexity: \mathcal{O}(\text{maxK} \cdot n)O(maxK⋅n), where \text{maxK}maxK is the maximum value of kk and nn is the length of a given string ss. We traverse a string of size nn and iterate kk times to decode each pattern of form \text{k[string]}k[string]. This gives us worst case time complexity as \mathcal{O}(\text{maxK} \cdot n)O(maxK⋅n).
*/