-
Notifications
You must be signed in to change notification settings - Fork 897
Expand file tree
/
Copy pathValidParentheses.swift
More file actions
34 lines (31 loc) · 903 Bytes
/
ValidParentheses.swift
File metadata and controls
34 lines (31 loc) · 903 Bytes
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
32
33
34
/**
* 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 {
switch char {
case "(", "[", "{":
stack.append(char)
case ")":
if stack.popLast() != "(" {
return false
}
case "]":
if stack.popLast() != "[" {
return false
}
case "}":
if stack.popLast() != "{" {
return false
}
default:
continue
}
}
return stack.isEmpty
}
}