本文主要是介绍Java | Leetcode Java题解之第385题迷你语法分析器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
class Solution {public NestedInteger deserialize(String s) {if (s.charAt(0) != '[') {return new NestedInteger(Integer.parseInt(s));}Deque<NestedInteger> stack = new ArrayDeque<NestedInteger>();int num = 0;boolean negative = false;for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (c == '-') {negative = true;} else if (Character.isDigit(c)) {num = num * 10 + c - '0';} else if (c == '[') {stack.push(new NestedInteger());} else if (c == ',' || c == ']') {if (Character.isDigit(s.charAt(i - 1))) {if (negative) {num *= -1;}stack.peek().add(new NestedInteger(num));}num = 0;negative = false;if (c == ']' && stack.size() > 1) {NestedInteger ni = stack.pop();stack.peek().add(ni);}}}return stack.pop();}
}
这篇关于Java | Leetcode Java题解之第385题迷你语法分析器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!