one pass C++ solution


  • 0
    P
    
    class Solution {
    public:
        NestedInteger deserialize(string s) {
            if(s.size() == 0) return NestedInteger();
            int flag = 1;
            int number = 0;
            if(s[0] != '['){
                for(int i = 0; i < s.size(); i ++){
                    if(s[i] == '-') flag = -1;
                    else number = number * 10 + (s[i] - '0');
                }
                return NestedInteger(flag * number);
            }
            stack<NestedInteger> st;
            for(int i = 0; i < s.size(); i ++){
                if(s[i] == ','){
                    number = 0;
                    flag = 1;
                }else if(s[i] == '['){
                    st.push(NestedInteger());
                }else if(s[i] == ']'){
                    NestedInteger tmp = st.top();
                    st.pop();
                    if(st.size() == 0) return tmp;
                    else {
                        st.top().add(tmp);
                    }
                }else if(s[i] == '-'){
                    flag = -1;
                }else{
                    number = number * 10 + (s[i] - '0');
                    if(!(s[i + 1] >= '0' && s[i + 1] <= '9')){
                        st.top().add(NestedInteger(number * flag));
                    }
                }
            }
            
        }
    };
    
    

Log in to reply
 

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