Swift solution


  • 0
    D
    func isValid(_ s: String) -> Bool {
        let string = s.map { String($0) }
        var stack: [String] = []
        
        for token in string {
            switch token {
                case "(", "{", "[":
                    stack.append(token)
                    break
                case ")":
                    if stack.isEmpty || stack.removeLast() != "(" {
                        return false
                    }
                case "}":
                    if stack.isEmpty || stack.removeLast() != "{" {
                        return false
                    }
                case "]":
                    if stack.isEmpty || stack.removeLast() != "[" {
                        return false
                    }
                default:
                    break
            }
        }
        
        return stack.isEmpty
    }
    
    

Log in to reply
 

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