Simple C++ solution using stack


  • 0
    Y
    class Solution {
    public:
        string decodeString(string s) {
            stack<char> st;
            for(int i = 0; i < s.length(); ++i)
            {
                if (s[i] == ']')
                {
                    string temp = "";
                    int num = 0;
                    while(!st.empty())
                    {
                        if(st.top() != '[')
                        {
                            temp += st.top();
                            st.pop();
                        }
                            
                        else
                        {
                            st.pop();
                            break;
                        }
                    }
                    
                    string num_str = "";
                    while(!st.empty())
                    {
                        if (isdigit(st.top()))
                            num_str += st.top();
                        else
                            break;
                        st.pop();
                    }
                    reverse(num_str.begin(), num_str.end());
                    num = atoi(num_str.c_str());
                    
                    reverse(temp.begin(), temp.end());
                    for(int j = 0; j < num; ++j)
                    {
                        for(int k = 0; k < temp.length(); ++k)
                            st.push(temp[k]);
                    }
                }
                else
                    st.push(s[i]);
            }
            string result = "";
            while(!st.empty())
            {
                result += st.top();
                st.pop();
            }
            reverse(result.begin(), result.end());
            return result;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.