# Decode String in C++

C++Server Side ProgrammingProgramming

Suppose we have an encoded string; we have to return its decoded string. The rule for encoding is: k[encoded_string], this indicates where the encoded_string inside the square brackets is being repeated exactly k times. We can assume that the original data does not contain any numeric characters and that digits are only for those repeat numbers, k. So if the input is like “1[ba]2[na]”, then the output will be “banana”.

To solve this, we will follow these steps −

• create one empty stack, set i := 0
• while i < size of a string
• if s[i] is ‘]’
• res := delete element from the stack and take only the string that is inside the square brackets.
• n := 0
• while stack is not empty, and stack top is one numeric character, then accommodate the numbers and form the actual integer as n
• for j in range 1 to n
• for x in range 0 to size of res
• insert res[x] into the stack
• otherwise insert s[i] into the stack
• increase i by 1
• ans := an empty string
• while stack is not empty
• ans := stack top element + ans
• pop from stack
• return ans

## Example(C++):

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string decodeString(string s) {
stack <char> st;
int i = 0;
while(i<s.size()){
if(s[i] == ']'){
string res = "";
while(st.top()!='['){
res = st.top() + res;
st.pop();
}
st.pop();
int n = 0;
int x = 1;
while(!st.empty() && st.top()>='0' && st.top()<='9'){
n = n + (st.top()-'0')*x;
x*=10;
st.pop();
}
for(int j = 1; j <= n; j++){
for(int x = 0; x < res.size();x++){
st.push(res[x]);
}
}
}
else{
st.push(s[i]);
}
i++;
}
string ans ="";
while(!st.empty()){
ans = st.top() + ans;
st.pop();
}
return ans;
}
};
main(){
Solution ob;
cout << ob.decodeString("1[ba]2[na]");
}

## Input

"1[ba]2[na]"

## Output

"banana"
Published on 27-Feb-2020 09:16:20