Given a nested list of integers represented as a string, implement a parser to deserialize it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Note: You may assume that the string is well-formed:
- String is non-empty.
- String does not contain white spaces.
- String contains only digits
0-9
,[
,-
,
,]
.
Example 1:
Given s = "324", You should return a NestedInteger object which contains a single integer 324.
Example 2:
Given s = "[123,[456,[789]]]", Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789.
这道题是实现“迷你解释器”,题目难度为Medium。
字符串中括号存在层层嵌套的情况,所以需要借助栈来记录遍历路径上的每层NestedInteger。遇到'['时,表明即将进入新一层链表,此时构造新的NestedInteger并进栈;遇到']'时,表明该层链表结束,此时出栈并将该层链表通过add函数加入上层链表中。数字在遍历到']'或','时结束,此时将数字构造的NestedInteger通过add函数加入栈顶链表中,处理过程中需要记录数字的起始位置。另外,栈中最好存储指针,能够降低空间复杂度。具体代码:
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Constructor initializes an empty nested list.
* NestedInteger();
*
* // Constructor initializes a single integer.
* NestedInteger(int value);
*
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Set this NestedInteger to hold a single integer.
* void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* void add(const NestedInteger &ni);
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class Solution {
public:
NestedInteger deserialize(string s) {
if(s[0] != '[') return NestedInteger(stoi(s));
stack<NestedInteger*> stk;
NestedInteger* ret = NULL;
int idx = 0;
for(int i=0; i<s.size(); ++i) {
if(s[i] == '[') {
stk.push(new NestedInteger());
if(!ret) ret = stk.top();
idx = i + 1;
}
else if(s[i] == ']' || s[i] == ',') {
if(idx != i)
stk.top()->add(NestedInteger(stoi(s.substr(idx, i-idx))));
if(s[i] == ']') {
NestedInteger* cur = stk.top();
stk.pop();
if(!stk.empty()) stk.top()->add(*cur);
}
idx = i + 1;
}
}
return *ret;
}
};