-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path17_Question.cpp
More file actions
74 lines (55 loc) · 1.5 KB
/
17_Question.cpp
File metadata and controls
74 lines (55 loc) · 1.5 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
// Given an encoded string s, decode it by expanding the pattern k[substring], where the substring inside brackets is written k times.
// Return the final decoded string.
// Examples:
// Input: s = "3[b2[ca]]"
// Output: bcacabcacabcaca
// Explanation:
// Inner substring "2[ca]" breakdown into "caca".
// Now , new string becomes "3[bcaca]"
// Similarly "3[bcaca]" becomes "bcacabcacabcaca" which is final result.
// Input: s = "3[ab]"
// Output: ababab
// Explanation: The substring "ab" is repeated 3 times, giving "ababab".
#include<bits/stdc++.h>
using namespace std;
string decodeString(string& s){
stack<char> st;
for(auto ch : s){
if(ch == ']'){
string new_str = "";
string num;
while (!st.empty() && st.top() != '[')
{
new_str = st.top() + new_str;
st.pop();
}
st.pop();
while(!st.empty() && isdigit(st.top())){
num = st.top() + num;
st.pop();
}
int n = stoi(num);
string temp = new_str;
for(int i=1; i<n; i++){
new_str += temp;
}
for(auto c : new_str){
st.push(c);
}
}else{
st.push(ch);
}
}
string res;
while(!st.empty()){
res = st.top() + res;
st.pop();
}
return res;
}
int main(){
string s;
cin>>s;
cout<<decodeString(s);
return 0;
}