Last active
March 15, 2019 16:39
-
-
Save aswinmprabhu/28618b270d7ebf7ac3c39e0d3913af4b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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