Swift solution


  • 0
    class Solution {
        func deserialize(_ s: String) -> NestedInteger {
            let chars = Array(s.characters)
            var stack = [NestedInteger]()
            var curr: NestedInteger? = nil
            var left = 0
            var right = 0
            
            while right < chars.count {
                let char = chars[right]
                if char == "[" {
                    if let current = curr {
                        stack.append(current)
                    }
                    curr = NestedInteger()
                } else if char == "]" {
                    let num = String(chars[left...right])
                    if !num.isEmpty {
                        curr?.add(elem: NestedInteger(Int(num)!))
                    }
                    if !stack.isEmpty {
                        let nestedInteger = stack.removeLast()
                        nestedInteger.add(elem: curr!)
                        curr = nestedInteger
                    }
                } else if char == "," {
                    if chars[right - 1] != "]" {
                        let num = String(chars[left...right])
                        curr?.add(elem: NestedInteger(Int(num)!))
                    }
                }
                left = right + 1
                right += 1
            }
            
            return curr!
        }
    }
    
    class NestedInteger {
        var list: [NestedInteger]?
        var integer: Int?
        
        public init(_ list: [NestedInteger]) {
            self.list = list
        }
        
        public init(_ integer: Int) {
            self.integer = integer
        }
        
        public init() {
            self.list = [NestedInteger]()
        }
        
        public func isInteger() -> Bool {
            return self.integer != nil
        }
        
        public func getInteger() -> Int {
            return self.integer!
        }
        
        public func setInteger(value: Int) {
            self.integer = value
        }
        
        public func add(elem: NestedInteger) {
            if list != nil {
                self.list?.append(elem)
            } else {
                self.list = [NestedInteger]()
                self.list?.append(elem)
            }
        }
        
        public func getList() -> [NestedInteger] {
            return self.list!
        }
    }
    

Log in to reply
 

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