Swift solution


  • 0
    class Solution {
        func isValid(_ s: String) -> Bool {
            if s.characters.count == 0 {
                return true
            }
            
            let characters = Array(s.characters)
            var stack = [Character]()
            
            for character in characters {
                if character == "(" {
                    stack.append(")")
                } else if character == "{" {
                    stack.append("}")
                } else if character == "[" {
                    stack.append("]")
                } else {
                    if let top = stack.last {
                        if character == top {
                            stack.removeLast()
                        } else {
                            return false
                        }
                    } else {
                        return false
                    }
                }
            }
            
            return stack.isEmpty
        }
    }
    

Log in to reply
 

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