Skip to content

Commit a99b00d

Browse files
committed
Mini stack
1 parent b81ff09 commit a99b00d

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

385.cpp

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
//coding:utf-8
2+
/*****************************************
3+
Program: Mini Parser
4+
Description:
5+
6+
Date: 2016-08-17 14:21:22
7+
Last modified: 2016-08-17 14:22:10
8+
GCC version: 4.9.3
9+
*****************************************/
10+
11+
/**
12+
* // This is the interface that allows for creating nested lists.
13+
* // You should not implement it, or speculate about its implementation
14+
* class NestedInteger {
15+
* public:
16+
* // Constructor initializes an empty nested list.
17+
* NestedInteger();
18+
*
19+
* // Constructor initializes a single integer.
20+
* NestedInteger(int value);
21+
*
22+
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
23+
* bool isInteger() const;
24+
*
25+
* // Return the single integer that this NestedInteger holds, if it holds a single integer
26+
* // The result is undefined if this NestedInteger holds a nested list
27+
* int getInteger() const;
28+
*
29+
* // Set this NestedInteger to hold a single integer.
30+
* void setInteger(int value);
31+
*
32+
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
33+
* void add(const NestedInteger &ni);
34+
*
35+
* // Return the nested list that this NestedInteger holds, if it holds a nested list
36+
* // The result is undefined if this NestedInteger holds a single integer
37+
* const vector<NestedInteger> &getList() const;
38+
* };
39+
*/
40+
41+
#include <stack>
42+
43+
class Solution {
44+
stack<NestedInteger> nstk;
45+
public:
46+
NestedInteger deserialize(string s) {
47+
int num = 0;
48+
int idx = 0;
49+
if(s[0] != '[')
50+
return NestedInteger(stoi(s));
51+
52+
int sign = 1;
53+
for(int i = 0; i < s.length(); ++i) {
54+
char c = s[i];
55+
if(c == '[') {
56+
nstk.push(NestedInteger());
57+
continue;
58+
} else if(c == ']' && nstk.size() > 1) {
59+
auto temp = nstk.top();
60+
nstk.pop();
61+
nstk.top().add(temp);
62+
} else if(c == ',') {
63+
continue;
64+
} else if(c == '-')
65+
sign = -1;
66+
else if(c >= '0' && c <= '9'){
67+
num = c - '0';
68+
while(i + 1 < s.length() && s[i + 1] >= '0' && s[i + 1] <= '9' )
69+
num = num * 10 + (s[(i++) + 1] - '0');
70+
num *= sign;
71+
if(!nstk.empty())
72+
nstk.top().add(NestedInteger(num));
73+
else
74+
nstk.push(NestedInteger(num));
75+
sign = 1;
76+
}
77+
}
78+
79+
return nstk.empty()? NestedInteger(): nstk.top();
80+
}
81+
};

0 commit comments

Comments
 (0)