# 385. 迷你语法分析器 Mini Parser【medium】【Stack】
给定一个字符串 s 表示一个整数嵌套列表,实现一个解析它的语法分析器并返回解析的结果 NestedInteger 。
列表中的每个元素只可能是整数或整数嵌套列表
示例 1:
```
输入:s = "324",
输出:324
解释:你应该返回一个 NestedInteger 对象,其中只包含整数值 324。
```
示例 2:
```
输入:s = "[123,[456,[789]]]",
输出:[123,[456,[789]]]
解释:返回一个 NestedInteger 对象包含一个有两个元素的嵌套列表:
1. 一个 integer 包含值 123
2. 一个包含两个元素的嵌套列表:
i. 一个 integer 包含值 456
ii. 一个包含一个元素的嵌套列表
a. 一个 integer 包含值 789
```
題解思路:
給定一個string,返回一個NestedInteger類別的list,其每個元素都是NestedInteger類別是整數對象。
從左到右遍歷s,這個字串由嵌套類型和數字和逗號、左中括號、右中括號組成。
1. 遇到左中括號`[`創建一個嵌套類型的NestedInteger實例,並把當前的NestedInteger物件加入棧中。
2. 遇到右中括號 `]` 結束當前NestedInteger物件,並把NestedInteger物件移出棧,然後繼續。
3. 遇到逗號 `,`如果comma不是接在右中括號後面的話,把str 接到當前的NestedInteger尾巴。
4. 更新index。l 跟 r,l代表數子型型的子字串開頭下標,r指向end+1子字串下標。
```java=
/**
* // 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) {
int l =0;
Stack<NestedInteger> stack = new Stack<>();
NestedInteger curr = null;
if(s.isEmpty()) return null;
if(s.charAt(0)!= '[') return new NestedInteger(Integer.valueOf(s));
for(int r = 0;r< s.length();r++){
if(s.charAt(r) == '['){
if(curr !=null){
stack.push(curr);
}
curr = new NestedInteger();
l = r+1;
}else if(s.charAt(r) == ']'){
String str = s.substring(l, r);
if(!str.isEmpty()){
curr.add(new NestedInteger(Integer.valueOf(str)));
}
if(!stack.isEmpty()){
NestedInteger pop = stack.pop();
pop.add(curr);
curr = pop;
}
l =r+1;
}else if(s.charAt(r) == ','){
if(s.charAt(r-1)!= ']'){
String str = s.substring(l, r);
curr.add(new NestedInteger(Integer.valueOf(str)));
}
l =r+1;
}
}
return curr;
}
}
```