zoukankan      html  css  js  c++  java
  • 385. Mini Parser

    Question

    385. Mini Parser

    Solution

    分析:用NI(count,list)来表示NestedInteger,则解析字符串[123,[456,[789]]]过程如下:

    # 首先将字符串转化为字符数组,遍历每个字符
    [      压栈操作 NI(0, null)
    123    给栈顶元素设置值 NI(0, NI(123))
    ,      不处理
    [      压栈操作 NI(0, NI(123)) | NI(0, null)
    456    给栈顶元素设置值 NI(0, NI(123)) | NI(0, 456)
    ,      不处理
    [      压栈操作 NI(0, NI(123)) | NI(0, NI(456)) | NI(0, null)
    789    给栈顶元素设置值 NI(0, NI(123)) | NI(0, NI(456)) | NI(0, NI(789))
    ]      出栈并将出栈后的元素添加到栈顶元素NI(0, NI(123)) | NI(0, [NI(456),NI(0, NI(789))])
    ]      出栈并将出栈后的元素添加到栈顶元素NI(0, [NI(123), NI(0, [NI(456), NI(0, NI(789))])])
    ]      不做处理
    # 栈中最后一个元素就是返回结果
    

    Java实现:

    public NestedInteger deserialize(String s) {
        if (!s.startsWith("[")) return new NestedInteger(Integer.parseInt(s));
        Stack<NestedInteger> stack = new Stack<>();
        // 123,[456,[789]]
    
        char[] arr = s.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            char ch = arr[i];
            if (ch == '[') {
                stack.push(new NestedInteger());
            } else if (ch == ']' & stack.size() > 1) {
                NestedInteger pop = stack.pop();
                stack.peek().add(pop);
            } else if (Character.isDigit(ch) || ch == '-') {
                boolean pos = true;
                if (ch == '-') {
                    pos = false;
                    i++;
                }
                int num = 0;
                while (i < arr.length && Character.isDigit(arr[i])) {
                    num *= 10;
                    num += arr[i++] - '0';
                }
                i--;
                stack.peek().add(new NestedInteger(pos ? num : -num));
            }
        }
        return stack.pop();
    }
    

    Reference

  • 相关阅读:
    (五)Redis在项目中应用
    股票收益最大问题
    (四)redigo
    (三)go-sql-driver
    为什么TCP要3次握手?4次挥手?
    分支预测
    事务隔离级别说明
    剑指offer解题思路锦集11-20题
    C++中的二义性问题
    memcached Vs redis
  • 原文地址:https://www.cnblogs.com/okokabcd/p/9175184.html
Copyright © 2011-2022 走看看