Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- 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:
-
Class Definition:
- Define a class
ValidParentheses
containing theisValid
method.
- Define a class
-
Stack Initialization:
- Use an array
leftSymbols
to simulate a stack.
- Use an array
-
Iteration:
- Iterate through each character in the string
s
.
- Iterate through each character in the string
-
Push Left Symbols:
- If the character is a left symbol (
(
,{
,[
), push it onto the stack.
- If the character is a left symbol (
-
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.
- If the character is a right symbol (
-
Return False for Invalid Symbols:
- If a right symbol does not have a matching left symbol at the top of the stack, return
false
.
- If a right symbol does not have a matching left symbol at the top of the stack, return
-
Check if Stack is Empty:
- At the end of the iteration, return
true
if the stack is empty (all symbols matched), otherwise returnfalse
.
- At the end of the iteration, return