LeetCode Mini Parser(栈操作)

来源:互联网 发布:阿里云有香港主机 编辑:程序博客网 时间:2024/06/06 17:25

题意:给出一个字符串,包含字符0-9,-,逗号,[,],计算封装后的整数

思路:用栈处理

1、如果遇到[,则入栈

2、如果遇到],并且栈中元素个数大于1,则取出栈顶元素,再将栈顶元素加入刚取现的元素

代码如下:

public class Solution {    public NestedInteger deserialize(String s) {        if (null == s) return null;        if (s.charAt(0) != '[') {            return new NestedInteger(Integer.parseInt(s));        }                int i = 0;        Stack<NestedInteger> stack = new Stack<>();        int len = s.length();        while (i < len) {            if (s.charAt(i) == '[') {                stack.push(new NestedInteger());                i++;                continue;            }                        if (s.charAt(i) == ']') {                if (stack.size() > 1) {                    NestedInteger tmp = stack.pop();                    stack.peek().add(tmp);                }                i++;                continue;            }                        if (s.charAt(i) == ',') {                i++;                continue;            }                        int sign = 1;            if (s.charAt(i) == '-') {                sign = -1;                i++;            }                        int sum = 0;            while (i < len && s.charAt(i) >= '0' && s.charAt(i) <= '9') {                sum = sum * 10 + s.charAt(i) - '0';                i++;            }                        stack.peek().add(new NestedInteger(sum * sign));        }                return stack.peek();    }}


0 0
原创粉丝点击