Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution
- {
- public:
- string decodeString(string s)
- {
- stack<char> st;
- string freq = "";
- stack<int> num;
- if (s.size() == 0)
- {
- return s;
- }
- int fr=0;
- for (int i = 0; i < s.size(); i++)
- {
- if (isdigit(s[i]))
- {
- freq.push_back(s[i]);
- }
- if (s[i] != ']' && !isdigit(s[i]))
- {
- st.push(s[i]);
- }
- else if (!st.empty() && s[i] == ']')
- {
- fr = fr +stoi(freq);
- num.push(fr);
- freq = "";
- fr=0;
- string res = "";
- while (st.top() != '[')
- {
- char ch = st.top();
- res.push_back(ch);
- st.pop();
- }
- st.pop(); // To remove '[' form the stack
- reverse(res.begin(), res.end());
- int t = 0;
- t = t + num.top();
- num.pop();
- while (t--)
- {
- for (int i = 0; i < res.size(); i++)
- {
- st.push(res[i]);
- }
- }
- }
- }
- string str = "";
- while (!st.empty())
- {
- str.push_back(st.top());
- st.pop();
- }
- reverse(str.begin(), str.end());
- return str;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment