/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * type NestedInteger struct {
 * }
 *
 * // Return true if this NestedInteger holds a single integer, rather than a nested list.
 * func (n NestedInteger) IsInteger() bool {}
 *
 * // 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
 * // So before calling this method, you should have a check
 * func (n NestedInteger) GetInteger() int {}
 *
 * // Set this NestedInteger to hold a single integer.
 * func (n *NestedInteger) SetInteger(value int) {}
 *
 * // Set this NestedInteger to hold a nested list and adds a nested integer to it.
 * func (n *NestedInteger) Add(elem NestedInteger) {}
 *
 * // Return the nested list that this NestedInteger holds, if it holds a nested list
 * // The list length is zero if this NestedInteger holds a single integer
 * // You can access NestedInteger's List element directly if you want to modify it
 * func (n NestedInteger) GetList() []*NestedInteger {}
 */
func deserialize(s string) *NestedInteger {
	ni := &NestedInteger{}
	if s == "[]" {
		return ni
	}
	n := len(s)
	if s[0] != '[' {
		i, _ := strconv.Atoi(s)
		ni.SetInteger(i)
		return ni
	}
	prev, comma := 1, nextComma(s, 1, n-1)
	for comma != -1 {
		ni.Add(*deserialize(s[prev:comma]))
		prev = comma + 1
		comma = nextComma(s, prev, n-1)
	}
	ni.Add(*deserialize(s[prev : n-1]))
	return ni
}

func nextComma(s string, beg, end int) int {
	for cnt, i := 0, beg; i < end; i++ {
		if s[i] == '[' {
			cnt++
		} else if s[i] == ']' {
			cnt--
		}
		if cnt == 0 && s[i] == ',' {
			return i
		}
	}
	return -1
}