Mini Parser Solutions in C++
Number 385
Difficulty Medium
Acceptance 33.8%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/mini-parser/// Author : Hao Chen// Date : 2016-08-24/*** // 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.size()==0) return NestedInteger();int pos = 0;if (s[pos]!='[') return atoni(s, pos);return helper(s, ++pos);}private:NestedInteger helper(string& s, int& pos) {NestedInteger ni;while ( s[pos] != ']' && pos < s.size() ) {if (s[pos]=='-' || isnum(s[pos])){ni.add(atoni(s, pos));}else if (s[pos] == '[') {pos++;ni.add(helper(s, pos));}else {pos++;}}pos++;return ni;}NestedInteger atoni(string& s, int& pos) {int sign = 1;int num = 0;if (s[pos]=='-') {sign = -1;pos++;}for (; pos < s.size(); pos++) {if (isnum(s[pos])) {num = num * 10 + s[pos] - '0';}else{break;}}return NestedInteger(sign * num);}bool isnum(char& c) {return (c >='0' && c <='9');}};