385. 迷你语法分析器
题目描述:
给定一个字符串 s 表示一个整数嵌套列表,实现一个解析它的语法分析器并返回解析的结果 NestedInteger 。
列表中的每个元素只可能是整数或整数嵌套列表。
解释:
后台实现了一个NestedInteger结构体,每一个NestedInteger实例有两种情况,数字和序列。
每一个序列可以包含序列和数字,而数字就是数字,不能包含序列。
默认是序列,如果要设置为数字通过setInteger函数实现。
比如[1, [2, 3], 4]这个NestedInteger的结构就是:
NestedInteger(序列):{
NestedInteger(数字):1
NestedInteger(序列):{
NestedInteger(数字):2
NestedInteger(数字):3
}
NestedInteger(数字):4
}
题解:
注意:
以下方法是题目自带的,不需要我们实现type NestedInteger struct {} // 如果这个NestedInteger保存单个整数,而不是嵌套的列表,则返回true func (n NestedInteger) IsInteger() bool {} // 如果它持有一个单个整数,返回这个NestedInteger持有的单个整数 // 如果这个NestedInteger持有一个嵌套的列表,结果是未定义的 // 所以在调用这个方法之前,你应该有一个检查 func (n NestedInteger) GetInteger() int {} // 将这个NestedInteger设置为保存单个整数。 func (n *NestedInteger) SetInteger(value int) {} // 设置这个NestedInteger来保存一个嵌套的列表,并向它添加一个嵌套的整数。 func (n *NestedInteger) Add(elem NestedInteger) {} // 如果它持有一个嵌套列表,返回这个NestedInteger持有的嵌套列表 // 如果这个NestedInteger保存单个整数,则列表长度为0 // 如果你想修改NestedInteger的List元素,你可以直接访问它 func (n NestedInteger) GetList() []*NestedInteger {}
func deserialize(s string) *NestedInteger {
// 如果首位不为'[' 说明只有一个数字,初始化一个序列,并设置为数字返回
if s[0] != '[' {
num, _ := strconv.Atoi(s)
ni := &NestedInteger{}
ni.SetInteger(num)
return ni
}
stack:=[]*NestedInteger{}
num:=0
negative:=false
for i, ch := range s {
if ch == '-' {
negative = true
} else if unicode.IsDigit(ch) { // 判断是否为数字
num = num*10 + int(ch-'0')
} else if ch == '[' {
stack = append(stack, &NestedInteger{})
} else if ch == ',' || ch == ']' {
if unicode.IsDigit(rune(s[i-1])) {
if negative {
num = -num
}
ni := NestedInteger{}
ni.SetInteger(num)
stack[len(stack)-1].Add(ni)
}
num, negative = 0, false
if ch == ']' && len(stack) > 1 {
stack[len(stack)-2].Add(*stack[len(stack)-1])
stack = stack[:len(stack)-1]
}
}
}
return stack[len(stack)-1]
}