LeetCode 385. 迷你语法分析器
原题链接
中等
/**
* // 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 {
private int u = 0;
private char[] cs;
private String s;
private NestedInteger build() {
// 解析 Integer
if(Character.isDigit(cs[u]) || cs[u] == '-') {
int k = u;
while(k < cs.length && (Character.isDigit(cs[k]) || cs[k] == '-'))
k ++;
int val = Integer.parseInt(s.substring(u, k));
u = k;
return new NestedInteger(val);
}
// 解析 [Integer, ...]
NestedInteger res = new NestedInteger();
u ++; // 跳过左括号
while(u < cs.length) {
// 如果是数或左括号, 继续添加
if(Character.isDigit(cs[u]) || cs[u] == '-' || cs[u] == '[')
res.getList().add(build());
// 如果是逗号,u++
else if(cs[u] == ',') u ++;
// 如果是右括号,退出循环
else if(cs[u] == ']') {
u ++;
break;
}
}
return res;
}
public NestedInteger deserialize(String s) {
this.cs = s.toCharArray();
this.s = s;
return build();
}
}