A Swift solution (119ms)


  • 0
    L
    func deserialize(_ s: String) -> NestedInteger {
        if s[s.startIndex] != "[" {
            let n = Int(s)!
            let nest = NestedInteger()
            nest.setInteger(n)
            return nest
        }
        var stack = [NestedInteger]()
        var num = ""
        for c in s.characters {
            if c == "[" {
                stack.append(NestedInteger())
            } else if c == "]"{
                let last = stack.removeLast()
                if !num.isEmpty {
                    let n = Int(num)!
                    let nest = NestedInteger()
                    nest.setInteger(n)
                    last.add(nest)
                    num = ""
                }
                if stack.isEmpty {
                    return last
                }
                if last.isInteger() {
                    stack[stack.count-1].setInteger(last.getInteger())
                } else {
                    stack[stack.count-1].add(last)
                }
            } else if c == "," {
                if let n = Int(num) {
                    let nest = NestedInteger()
                    nest.setInteger(n)
                    stack[stack.count-1].add(nest)
                    num = ""
                }
            } else {
                num.append(c)
            }
        }
        return NestedInteger()
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.