Swift Solution Using Stack, easy Understanding


  • 0
    func isValid(s: String) -> Bool {
        
        // construct a STACK
        struct Stack<Element> {
            
            private var container = [Element]()
            var topElement: Element? {
                get {
                    return container.last
                }
            }
            
            mutating func push(element: Element) {
                container.append(element)
            }
            
            mutating func pop() -> Element? {
                guard container.count != 0 else { return nil }
                return container.removeLast()
            }
            func isEmpty() -> Bool {
                return container.count == 0
            }
            
        }
        
        // construct a enum include all Character
        enum Brace: Character {
            case LP = "("
            case RP = ")"
            case LB = "["
            case RB = "]"
            case LBR = "{"
            case RBR = "}"
        }
        
        
        var stack = Stack<Brace>()
        for char in s.characters {
            let brace = Brace(rawValue: char)
            guard let br = brace else { return false }
            
            switch br {
            case .LP,.LB,.LBR:
                stack.push(br)
            case .RP,.RB,.RBR:
                guard let top = stack.topElement else  { return false }
                if (br == .RP && top == .LP)
                    || (br == .RB && top == .LB)
                    || (br == .RBR && top == .LBR) {
                    stack.pop()
                } 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.