forked from yuyongwei/Algorithms-In-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvalidParentheses.swift
More file actions
27 lines (23 loc) · 853 Bytes
/
Copy pathvalidParentheses.swift
File metadata and controls
27 lines (23 loc) · 853 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
/*
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
https://leetcode.com/problems/valid-parentheses/
*/
func isValid(_ s: String) -> Bool {
guard !s.isEmpty else { return true }
let parens: [Character: Character] = ["(", ")", "[": "]", "{": "}"]
var stack = [Character]()
for c in s {
if c == "(" || c == "[" || c == "{" {
stack.append(c)
} else {
guard !stack.isEmpty else { return false }
let key = stack.removeLast()
if parents[key] != c { return false }
}
}
return stack.isEmpty
}