-
Notifications
You must be signed in to change notification settings - Fork 0
/
Contents.swift
46 lines (43 loc) · 1.25 KB
/
Contents.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// LeetCode: https://leetcode.com/problems/valid-parentheses/description/
class Solution {
func isValid(_ s: String) -> Bool {
var arr: [Character] = []
for c in s {
switch c {
case "(", "[", "{":
arr.append(c)
case ")":
let char = pop(&arr)
if nil == char || char != "(" {
return false
}
case "]":
let char = pop(&arr)
if nil == char || char != "[" {
return false
}
case "}":
let char = pop(&arr)
if nil == char || char != "{" {
return false
}
default:
break
}
}
return arr.count == 0
}
private func pop(_ arr: inout [Character]) -> Character? {
guard arr.count > 0 else {
return nil
}
return arr.remove(at: arr.count-1)
}
}
let solution = Solution()
print("\(solution.isValid("()"))")
print("\(solution.isValid("()[]{}"))")
print("\(solution.isValid("(]"))")
print("\(solution.isValid("([)]"))")
print("\(solution.isValid("{[]}"))")
print("\(solution.isValid("["))")