Skip to content

Instantly share code, notes, and snippets.

@aswinmprabhu
Last active March 15, 2019 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aswinmprabhu/28618b270d7ebf7ac3c39e0d3913af4b to your computer and use it in GitHub Desktop.
Save aswinmprabhu/28618b270d7ebf7ac3c39e0d3913af4b to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
string decode(string str)
{
stack<int> numstack;
stack<char> charstack;
string nstr;
for (int i = 0; str[i] != '\0'; i++)
{
if (isdigit(str[i]))
{
nstr += str[i];
}
else if (str[i] == '[')
{
charstack.push(str[i]);
int no = stoi(nstr);
numstack.push(no);
nstr = "";
}
else if (str[i] == ']')
{
string poppedstr;
char c = charstack.top();
charstack.pop();
while (c != '[')
{
poppedstr += c;
c = charstack.top();
charstack.pop();
}
reverse(poppedstr.begin(), poppedstr.end());
int no = numstack.top();
numstack.pop();
for (int x = 0; x < no; x++)
for (int j = 0; j < poppedstr.length(); j++)
charstack.push(poppedstr[j]);
}
else
{
charstack.push(str[i]);
}
}
string ans;
while (!charstack.empty())
{
ans += charstack.top();
charstack.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
int main()
{
string str;
cout << "Enter the string to be decoded : ";
cin >> str;
string ans = decode(str);
cout << ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment