OneCompiler

decoding the string

112

decoding the string

i/p:

3[a]2[bc]

o/p:

aaabcbc

Following is sample C++ code.

#include <iostream>
using namespace std;
  int stringtointeger(string s){
    int ans=0;
    for(char nxt:s){
      ans*=10;
      ans+=nxt-'0';
    }
    return ans;
  }
  string decodestring(string s){
    string ans="";
    int prev=0;
    int repetition=0;
    int depth=0;
    for(int i=0;i<s.size();i++){
      if(depth==0 && 'a'<=s[i] && s[i]<='z'){
        ans.push_back(s[i]);
        prev=i+1;
      }
      if(s[i]=='['){
        depth++;
        if(depth==1){
          repetition=stringtointeger(s.substr(prev,i-prev));
          prev=i+1;
        }
      }
      else if(s[i]==']'){
        depth--;
        if(depth==0){
          while(repetition>0){
            ans+=decodestring(s.substr(prev,i-prev));
            repetition--;
          }
          prev=i+1;
        }
      }
    }
    return ans;
  }
int main() 
{
    string a;
    cin>>a;
    string b=decodestring(a);
    cout<<b;
}