leetcode 385. Mini Parser | 385. 迷你语法分析器(Java)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 385. Mini Parser | 385. 迷你语法分析器(Java)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/mini-parser/
題解
只要有耐心分析清楚每一種狀態就可以啦。
/*** // This is the interface that allows for creating nested lists.* // You should not implement it, or speculate about its implementation* public interface NestedInteger {* // Constructor initializes an empty nested list.* public NestedInteger();** // Constructor initializes a single integer.* public NestedInteger(int value);** // @return true if this NestedInteger holds a single integer, rather than a nested list.* public boolean isInteger();** // @return the single integer that this NestedInteger holds, if it holds a single integer* // Return null if this NestedInteger holds a nested list* public Integer getInteger();** // Set this NestedInteger to hold a single integer.* public void setInteger(int value);** // Set this NestedInteger to hold a nested list and adds a nested integer to it.* public void add(NestedInteger ni);** // @return the nested list that this NestedInteger holds, if it holds a nested list* // Return empty list if this NestedInteger holds a single integer* public List<NestedInteger> getList();* }*/ class Solution {public NestedInteger deserialize(String s) {if (s.charAt(0) != '[') return new NestedInteger(Integer.parseInt(s));Stack<NestedInteger> stack = new Stack<>();NestedInteger cur = new NestedInteger();int num = 0;int sn = 1; // sign=1,-1boolean pending = false; // 未清算標記,避免符號之間重復清算for (int i = 0; i < s.length(); i++) {if (s.charAt(i) == ',') {// 清算上一數字if (pending) {cur.add(new NestedInteger(num * sn));num = 0;sn = 1;pending = false;}} else if (s.charAt(i) == '[') {// 清算上一數字if (pending) {cur.add(new NestedInteger(num * sn));num = 0;sn = 1;pending = false;}// 當前層NI存入棧中stack.push(cur);// 新開一層NIcur = new NestedInteger();} else if (s.charAt(i) == ']') {// 清算上一數字if (pending) {cur.add(new NestedInteger(num * sn));num = 0;sn = 1;pending = false;}// 當前層NI結束,把當前NI加入到上一層NestedInteger old = stack.pop();old.add(cur);cur = old;} else if (s.charAt(i) == '-') {sn = -1;pending = true;} else {num *= 10;num += (s.charAt(i) - '0');pending = true;}}return cur.getList().get(0); // 解開多包的一層[]} }總結
以上是生活随笔為你收集整理的leetcode 385. Mini Parser | 385. 迷你语法分析器(Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 377. Combin
- 下一篇: leetcode 382. Linked