Algorithm
Leet Code Easy
[Swift] Valid Parentheses
[Swift] 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.
Example
Input: s = "()"
Output: true
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: false
Input: s = "([)]"
Output: false
Input: s = "{[]}"
Output: true
문제 이해
코드
func isValid(_ s: String) -> Bool {
var stack: [Character] = []
if s.count == 1 {
return false
}
for c in s {
if c == "(" {
stack.append(")")
} else if c == "[" {
stack.append("]")
} else if c == "{" {
stack.append("}")
} else {
if !stack.isEmpty {
let pop = stack.removeLast()
if pop != c {
return false
}
} else {
return false
}
}
}
return stack.isEmpty
}
풀이
-
다른 분의 멋진 코드
-
잘 배웠습니다.
-
댓글남기기