描述
题目要求:给定一个字符串 s 表示一个整数嵌套列表,实现一个解析它的语法分析器并返回解析的结果 NestedInteger。
列表中的每个元素只可能是整数或整数嵌套列表。
示例 1:
输入: s = "324", 输出: 324 解释: 你应该返回一个 NestedInteger 对象,其中只包含整数值 324。
示例 2:
输入: s = "[123,[456,[789]]]", 输出: [123,[456,[789]]] 解释: 返回一个 NestedInteger 对象包含一个有两个元素的嵌套列表:
1. 一个 integer 包含值 123
2. 一个包含两个元素的嵌套列表:
i. 一个 integer 包含值 456
ii. 一个包含一个元素的嵌套列表
a. 一个 integer 包含值 789
提示:
1 <= s.length <= 5 * 10^4s由数字、方括号"[]"、负号'-'、逗号','组成- 用例保证
s是可解析的NestedInteger - 输入中的所有值的范围是
[-10^6, 10^6]
这道题的核心思路是遍历字符串,遇到 '[' 就创建一个新的嵌套列表,遇到 ']' 就结束当前列表,遇到数字就解析成整数,遇到逗号就分隔元素。我们可以用栈来维护嵌套结构,也可以用递归的方式来处理。
题解答案
下面是完整的 Swift 解决方案:
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* public func isInteger() -> Bool
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // Return nil if this NestedInteger holds a nested list
* public func getInteger() -> Int?
*
* // Set this NestedInteger to hold a single integer.
* public func setInteger(value: Int)
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* public func add(elem: NestedInteger)
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // Return nil if this NestedInteger holds a single integer
* public func getList() -> [NestedInteger]?
* }
*/
class Solution {
func ( : ) -> {
s.hasPrefix() {
num (s)
ni ()
ni.setInteger(value: num)
ni
}
stack: [] []
num: ?
isNegative
char s {
char {
ni ()
stack.append(ni)
} char {
isNegative
} char.isNumber {
digit ((char))
num (num ) digit
} char char {
n num {
value isNegative n : n
ni ()
ni.setInteger(value: value)
last stack.last {
last.add(elem: ni)
} {
stack.append(ni)
}
num
isNegative
}
char {
stack.count {
current stack.removeLast()
stack.last.add(elem: current)
}
}
}
}
stack.first ()
}
}


