采用这种方式,在一些奇奇怪怪的样例上会出错,神烦的样例。主要错出现在对空集合的判断上,无法知道这到底是一个空集,还是个链表。本想通过逗号的位置判断,但还是会出错。于是在一开始就对是否为空集进行判断,于是修改代码:
if(s[i]=='['||s[i]==',')
{
if(s[i+1]==']')
{
NestedInteger num;
nums.push(num);
i+=2;
}
else
signal.push(s[i++]);
}
}
/**
* // 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) {
stack<NestedInteger> nums;
stack<char> signal;
int i=0;
while(i<s.size())
{
if(s[i]=='['||s[i]==',')
{
if(s[i+1]==']')
{
NestedInteger num;
nums.push(num);
i+=2;
}
else
signal.push(s[i++]);
}
else if(s[i]>='0'&&s[i]<='9')
{
int temp=0;
while(i<s.size()&&s[i]>='0'&&s[i]<='9')
temp=temp*10+s[i++]-'0';
NestedInteger num(temp);
nums.push(num);
//cout<<temp<<endl;
}
else if(s[i]=='-')
{
int temp=0;
i++;
while(i<s.size()&&s[i]>='0'&&s[i]<='9')
temp=temp*10+s[i++]-'0';
temp=-temp;
NestedInteger num(temp);
nums.push(num);
}
else if(s[i]==']')
{
stack<NestedInteger> temp;
if(!nums.empty())
{
temp.push(nums.top());
nums.pop();
}
while(signal.top()==',')
{
temp.push(nums.top());
nums.pop();
signal.pop();
}
signal.pop();
NestedInteger num;
while(!temp.empty())
{
num.add(temp.top());
temp.pop();
}
nums.push(num);
i++;
}
}
return nums.top();
}
};