forked from banjodayo39/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidParentheses.swift
31 lines (28 loc) · 1009 Bytes
/
ValidParentheses.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Question Link: https://leetcode.com/problems/valid-parentheses/
* Primary idea: Use a stack to see whether the peek left brace is correspond to the current right one
* Time Complexity: O(n), Space Complexity: O(n)
*/
class ValidParentheses {
func isValid(_ s: String) -> Bool {
var stack = [Character]()
for char in s {
if char == "(" || char == "[" || char == "{" {
stack.append(char)
} else if char == ")" {
guard stack.count != 0 && stack.removeLast() == "(" else {
return false
}
} else if char == "]" {
guard stack.count != 0 && stack.removeLast() == "[" else {
return false
}
} else if char == "}" {
guard stack.count != 0 && stack.removeLast() == "{" else {
return false
}
}
}
return stack.isEmpty
}
}