알고리즘
[Swift] LeetCode - 20. Valid Parentheses
고고
2022. 2. 15. 12:26
문제: https://leetcode.com/problems/valid-parentheses/
Valid Parentheses - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
import Foundation
class Solution {
func isValid(_ s: String) -> Bool {
var stack = [Character]()
for char in s {
if char == "(" || char == "{" || char == "[" {
stack.append(char)
} else {
if stack.isEmpty { return false }
let last = stack.removeLast()
if last == "(" && char == ")" {
continue
} else if last == "{" && char == "}" {
continue
} else if last == "[" && char == "]" {
continue
} else {
return false
}
}
}
return stack.count == 0
}
}