解析:
由于字符串是递归定义的,我们自然也可以递归求解,当然,我们不用完全依赖递归函数,可以通过栈来模拟,从左到右遍历字符串:
- 如果当前的值是
[,则说明我们需要创建一个NestedInteger来接收后面的值,那么就要new NestedInteger()并放到栈顶 - 如果当前的值是
],则说明我们栈顶的NestedInteger已经构建完毕了,我们可以把他pop出来,并将他的值添加到当前栈顶(当前栈顶已经是另一个NestedInteger了)的列表里去 - 如果当前是
,,视为分隔符,忽略 - 如果当前是
数字,则我们将这个数字看作一个单独的NestedInteger,将它的值算出来,并添加到栈顶NestedInteger的列表里去
另外,因为栈中一开始是没有元素的,为了避免分类讨论栈是否为空,我们给栈内默认添加一个元素
代码如下:
cpp
class Solution {
public:
NestedInteger deserialize(string s) {
stack<NestedInteger> st;
st.push(* new NestedInteger());
for(int i=0;i<s.length();){
if(s[i]==',') {i++;continue ;}
else if(s[i]=='['){
st.push(* new NestedInteger());
i++;
}
else if(s[i]==']'){
auto &top=st.top();
st.pop();
st.top().add(top);
i++;
}
else {
int j=i;
bool flag=0;
while(j<s.length()&&(s[j]<='9'&&s[j]>='0'||s[j]=='-')) j++;
st.top().add(* new NestedInteger(stoi(s.substr(i,j-i))));
i=j;
}
}
return st.top().getList()[0];
}
};
java
class Solution {
public NestedInteger deserialize(String s) {
Stack<NestedInteger> stack=new Stack<>();
stack.push(new NestedInteger());
for(int i=0;i<s.length();){
if(s.charAt(i)==',') {i++;continue ;}
else if(s.charAt(i)=='['){
stack.push(new NestedInteger());
i++;
}
else if(s.charAt(i)==']'){
NestedInteger top=stack.peek();
stack.pop();
stack.peek().add(top);
i++;
}
else {
int j=i;
while(j<s.length()&&(s.charAt(j)<='9'&&s.charAt(j)>='0'||s.charAt(j)=='-')) j++;
stack.peek().add(new NestedInteger(Integer.parseInt(s.substring(i,j))));
i=j;
}
}
return stack.peek().getList().get(0);
}
}