Easy C++ with stack


  • 0
    J

    Using stack to do the bracket match. deal with number in a while-loop and ignore the ,.

    class Solution {
    public:
        NestedInteger deserialize(string s) {
            stack<NestedInteger> st;
            string num;
            int size = s.size();
            NestedInteger ni;
            for(int i = 0; i < size; i++) {
                if(s[i] == '[') {
                    st.push(NestedInteger());
                } else if(s[i] == ']') {
                    if(st.size() > 1) {
                        ni = st.top();
                        st.pop();
                        st.top().add(ni);
                    }
                } else if(s[i] != ',') {
                    while(('0' <= s[i] && s[i] <= '9') || s[i] == '-') {
                        num += s[i++];
                    }
                    if(!st.empty()) {
                        st.top().add(NestedInteger(stoi(num, nullptr, 10)));
                    } else {
                        st.push(NestedInteger(stoi(num, nullptr, 10)));
                    }
                    i--;
                    num = "";
                }
            }
            return st.top();
        }
    };
    

  • 0
    J

    (Update) remove the stack empty check using an empty NestedInteger outside.

    class Solution {
    public:
        NestedInteger deserialize(string s) {
            stack<NestedInteger> st;
            string num;
            NestedInteger ni;
            int size = s.size();
            st.push(NestedInteger());
            for(int i = 0; i < size; i++) {
                if(s[i] == '[') {
                    st.push(NestedInteger());
                } else if(s[i] == ']') {
                    ni = st.top();st.pop();
                    st.top().add(ni);
                } else if(s[i] != ',') {
                    while(('0' <= s[i] && s[i] <= '9') || s[i] == '-') {
                        num += s[i++];
                    }
                    st.top().add(NestedInteger(stoi(num, nullptr, 10)));
                    i--;
                    num.clear();
                }
            }
            return st.top().getList().front();
        }
    };
    

Log in to reply
 

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