Solution in Swift with readability


  • 0
    J

    Clean code in Swift

    class Solution {
        
        func isOpen(_ ch: Character) -> Bool {
            return (ch == "(" || ch == "{" || ch == "[")    
        }
        
        
        func isMatch(_ openChar: Character, _ closeChar: Character) -> Bool {
            let match: [Character : Character] = ["(" : ")",
                                                  "{" : "}",
                                                  "[" : "]"]
            
            if let closech = match[openChar], closech == closeChar {
                return true
            }
            
            return false
        }
        
        
        func isValid(_ s: String) -> Bool {
            var stack: [Character] = []
            
            for ch in s.characters {
                if self.isOpen(ch) {
                    stack.append(ch)
                } else if let top = stack.last, self.isMatch(top, ch) {
                    stack.removeLast()
                } else {
                    return false
                }
            }
            
            return stack.isEmpty == true
        }
    }
    

Log in to reply
 

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