Using stack


  • 0
    Z
    public class Solution {
        public NestedInteger deserialize(String s) {
            NestedInteger res = null;
            Stack<NestedInteger> st = new Stack<NestedInteger>();
            Integer val = null;
            int sign = 1;
            for(int i=0;i<s.length();i++) {
                char c = s.charAt(i);
                if(c == '[') {
                    NestedInteger tmp = new NestedInteger();
                    if(res == null) res = tmp;
                    if(!st.isEmpty()) st.peek().add(tmp);
                    st.push(tmp);
                }else if(c >= '0' && c<= '9') {
                    val = (val==null ? 0:val)*10 + (c-'0')*sign;
                }else if(c == '-') {
                    sign = -1;
                }else if(c == ',') {
                    if(val != null) st.peek().add(new NestedInteger(val));
                    val = null;
                    sign = 1;
                }else if(c == ']') {
                    if(val != null) st.peek().add(new NestedInteger(val));
                    st.pop();
                    val= null;
                }
            }
            return res == null ? new NestedInteger(Integer.parseInt(s)) : res;
        }
    }
    

Log in to reply
 

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