How do I implement the valid parentheses checker in Swift?

Implementing a valid parentheses checker in Swift involves using a stack to keep track of opening parentheses and matching them with closing parentheses. Here’s a simple example of how to achieve this:

func isValidParentheses(_ s: String) -> Bool {
    var stack = [Character]()

    for char in s {
        if char == "(" || char == "{" || char == "[" {
            stack.append(char)
        } else if char == ")" {
            if stack.isEmpty || stack.removeLast() != "(" {
                return false
            }
        } else if char == "}" {
            if stack.isEmpty || stack.removeLast() != "{" {
                return false
            }
        } else if char == "]" {
            if stack.isEmpty || stack.removeLast() != "[" {
                return false
            }
        }
    }

    return stack.isEmpty
}

// Example usage:
print(isValidParentheses("{[()]}")) // true
print(isValidParentheses("{[(])}")) // false

valid parentheses parentheses checker Swift programming data structures algorithms