Hustlingbeast_Anish

Untitled

Mar 27th, 2022
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.53 KB | None | 0 0
  1. class Solution
  2. {
  3. public:
  4.     string decodeString(string s)
  5.     {
  6.         stack<char> st;
  7.         string freq = "";
  8.         stack<int> num;
  9.         if (s.size() == 0)
  10.         {
  11.             return s;
  12.         }
  13.         int fr=0;
  14.         for (int i = 0; i < s.size(); i++)
  15.         {
  16.             if (isdigit(s[i]))
  17.             {
  18.                 freq.push_back(s[i]);
  19.             }
  20.  
  21.             if (s[i] != ']' && !isdigit(s[i]))
  22.             {
  23.                 st.push(s[i]);
  24.             }
  25.             else if (!st.empty() && s[i] == ']')
  26.             {
  27.                 fr = fr +stoi(freq);
  28.                 num.push(fr);
  29.                 freq = "";
  30.                 fr=0;
  31.                 string res = "";
  32.  
  33.                 while (st.top() != '[')
  34.                 {
  35.                     char ch = st.top();
  36.                     res.push_back(ch);
  37.                     st.pop();
  38.                 }
  39.                 st.pop(); // To remove '[' form the stack
  40.  
  41.                 reverse(res.begin(), res.end());
  42.                 int t = 0;
  43.                 t = t + num.top();
  44.                 num.pop();
  45.                 while (t--)
  46.                 {
  47.                     for (int i = 0; i < res.size(); i++)
  48.                     {
  49.                         st.push(res[i]);
  50.                     }
  51.                 }
  52.             }
  53.         }
  54.         string str = "";
  55.         while (!st.empty())
  56.         {
  57.             str.push_back(st.top());
  58.             st.pop();
  59.         }
  60.         reverse(str.begin(), str.end());
  61.         return str;
  62.     }
  63. };
Advertisement
Add Comment
Please, Sign In to add comment