题目
mini-parser
算法
* 模拟
* 栈
* istringstream
代码
* 模拟
class Solution {
public:
NestedInteger deserialize(string s) {
if (s.empty()) return NestedInteger();
if (s[0] != '[') return NestedInteger(stoi(s));
if (s.size() <= 2) return NestedInteger();
NestedInteger res;
int start = 1, cnt = 0;
for (int i = 1; i < s.size(); ++i) {
if (cnt == 0 && (s[i] == ',' || i == s.size() - 1)) {
res.add(deserialize(s.substr(start, i - start)));
start = i + 1;
} else if (s[i] == '[') ++cnt;
else if (s[i] == ']') --cnt;
}
return res;
}
};
* 栈
class Solution {
public:
NestedInteger deserialize(string s) {
if (s.empty()) return NestedInteger();
if (s[0] != '[') return NestedInteger(stoi(s));
stack<NestedInteger> st;
int start = 1;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '[') {
st.push(NestedInteger());
start = i + 1;
} else if (s[i] == ',' || s[i] == ']') {
if (i > start) {
st.top().add(NestedInteger(stoi(s.substr(start, i - start))));
}
start = i + 1;
if (s[i] == ']') {
if (st.size() > 1) {
NestedInteger t = st.top(); st.pop();
st.top().add(t);
}
}
}
}
return st.top();
}
};
* istringtream
class Solution {
public:
NestedInteger deserialize(string s) {
istringstream in(s);
return deserialize(in);
}
NestedInteger deserialize(istringstream& in) {
int num;
if (in >> num) return NestedInteger(num);
in.clear();
in.get();
NestedInteger list;
while (in.peek() != ']') {
list.add(deserialize(in));
if (in.peek() == ',') {
in.get();
}
}
in.get();
return list;
}
};