Easy
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
Example 1:
Input: s = “()”
Output: true
Example 2:
Input: s = “()[]{}”
Output: true
Example 3:
Input: s = “(]”
Output: false
Example 4:
Input: s = “([)]”
Output: false
Example 5:
Input: s = “{[]}”
Output: true
Constraints:
1 <= s.length <= 104
s
consists of parentheses only '()[]{}'
.To solve the Valid Parentheses problem in Swift with a Solution
class, we’ll use a stack data structure. Here are the steps:
Solution
class with a method named isValid
that takes a string s
as input and returns a boolean indicating whether the string contains valid parentheses.s
.'('
, '{'
, or '['
), push it onto the stack.')'
, '}'
, or ']'
), check if the stack is empty. If it is, return false
because there’s no matching opening parenthesis for the current closing parenthesis.false
.s
, check if the stack is empty. If it’s not empty, return false
because there are unmatched opening parentheses remaining.true
because all parentheses are valid.Here’s the implementation:
class Solution {
func isValid(_ s: String) -> Bool {
var stack = [Character]()
for char in s {
if char == "(" || char == "[" || char == "{" {
stack.append(char)
} else if char == ")" && !stack.isEmpty && stack.last == "(" {
stack.popLast()
} else if char == "}" && !stack.isEmpty && stack.last == "{" {
stack.popLast()
} else if char == "]" && !stack.isEmpty && stack.last == "[" {
stack.popLast()
} else {
return false
}
}
return stack.isEmpty
}
}
This implementation provides a solution to the Valid Parentheses problem in Swift using a stack data structure.