forked from diwu/LeetCode-Solutions-in-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Easy_020_Valid_Parentheses.swift
48 lines (38 loc) · 1.24 KB
/
Easy_020_Valid_Parentheses.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
47
48
/*
https://leetcode.com/problems/valid-parentheses/
#20 Valid_Parentheses
Level: easy
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Inspired by @exodia at https://leetcode.com/discuss/21440/sharing-my-simple-cpp-code-with-2ms
*/
import Foundation
private extension String {
func randomAccessCharacterArray() -> Array<Character> {
return Array(self)
}
}
struct Easy_020_Valid_Parentheses {
// t=O(N), s=O(N)
static func isValid(_ s: String) -> Bool {
let charArr = s.randomAccessCharacterArray()
let dict: Dictionary<Character, Character> = [
"}":"{",
"]":"[",
")":"("
]
var stack: Array<Character> = []
for char in charArr {
if char == "}" || char == ")" || char == "]" {
if stack.isEmpty || stack.last != dict[char] {
return false
} else {
stack.removeLast()
}
} else {
stack.append(char)
}
}
return stack.isEmpty
}
}