How to check balanced Parenthesis in swift ?

[Question]: Check if the given string has balanced parenthesis //Example 1: // //Input: s = "()" //Output: true //Example 2: // //Input: s = "[](){}" //Output: true //Example 3: // //Input: s = "(}" //Output: false

func isValid(_ s: String) -> Bool {
    guard s.count % 2 == 0 else { return false }
    
    var stack: [Character] = []
    //Here we are maintaing stack . adding element with close bracket & removing values from stack if the braces not matched.
    for ch in s {
        switch ch {
        case "(": stack.append(")")
        case "[": stack.append("]")
        case "{": stack.append("}")
        default:
            // so we are checking the order in which we inserted the bracket if it does not matched with last pop It's unbalanced '
            if stack.isEmpty || stack.removeLast() != ch {
                return false
            }
        }
    }
    
    return stack.isEmpty
}

Leave a Comment

Your email address will not be published. Required fields are marked *