Jun 28, 2024 dsa

Valid Parentheses

Valid Parentheses

Given a string s containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

To convert the given Java code for validating parentheses into Swift, you can use a similar approach with a stack. Swift’s Array type can be used as a stack because it provides append (push) and removeLast (pop) operations.

Swift Implementation:

Here’s the Swift implementation of the isValid method to check if a string containing parentheses is valid:

var exp = "[()]{}{[()()]()}"
func isValid(_ s: String) -> Bool {
    var leftsymbols = [Character]()
    var b = 0
    var c = 0
    var d = 0
    for char in s {
        switch char {
        case"{" : b += 1
        case"}" : b -= 1
        case"[" : c += 1
        case"]" : c -= 1
        case"(" : d += 1
        case")" : d -= 1
        default: break
            
        }
    }
    if ((b == 0) && (c == 0)  && (d == 0)) {
        return true
    }else {
        return false
    }
}

2nd solution

class ValidParentheses {
    func isValid(_ s: String) -> Bool {
        // Stack to store left symbols
        var leftSymbols = [Character]()
        
        // Loop for each character of the string
        for c in s {
            // If left symbol is encountered
            if c == "(" || c == "{" || c == "[" {
                leftSymbols.append(c)
            }
            // If right symbol is encountered
            else if c == ")" && !leftSymbols.isEmpty && leftSymbols.last == "(" {
                leftSymbols.removeLast()
            } else if c == "}" && !leftSymbols.isEmpty && leftSymbols.last == "{" {
                leftSymbols.removeLast()
            } else if c == "]" && !leftSymbols.isEmpty && leftSymbols.last == "[" {
                leftSymbols.removeLast()
            }
            // If none of the valid symbols is encountered
            else {
                return false
            }
        }
        return leftSymbols.isEmpty
    }
}

// Example usage:
let validator = ValidParentheses()
let result = validator.isValid("()[]{}")
print(result)  // Output: true

Explanation:

  1. Class Definition:
    • Define a class ValidParentheses containing the isValid method.
  2. Stack Initialization:
    • Use an array leftSymbols to simulate a stack.
  3. Iteration:
    • Iterate through each character in the string s.
  4. Push Left Symbols:
    • If the character is a left symbol ((, {, [), push it onto the stack.
  5. Pop Matching Right Symbols:
    • If the character is a right symbol (), }, ]), check if the stack is not empty and the top of the stack is the matching left symbol.
    • If so, pop the stack.
  6. Return False for Invalid Symbols:
    • If a right symbol does not have a matching left symbol at the top of the stack, return false.
  7. Check if Stack is Empty:
    • At the end of the iteration, return true if the stack is empty (all symbols matched), otherwise return false.
Index