-
Notifications
You must be signed in to change notification settings - Fork 21
/
ValidParentheses.swift
38 lines (32 loc) 路 1.09 KB
/
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
32
33
34
35
36
37
38
//
// ValidParentheses.swift
// LeetCode
//
// Created by 榛庤档澶儙 on 25/11/2017.
// Copyright 漏 2017 lizhaotailang. All rights reserved.
//
// 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.
//
// Accepted. See [ValidParenthesesTests](./LeetCodeTests/ValidParenthesesTests.swift) for the test cases.
//
import Foundation
class ValidParentheses {
func isValid(_ s: String) -> Bool {
if s.isEmpty || s.count == 1 {
return false
}
var list: [Character] = []
for char in s {
if !list.isEmpty && ((char == ")" && list[list.count - 1] == "(")
|| (char == "]" && list[list.count - 1] == "[")
|| (char == "}" && list[list.count - 1] == "{")) {
list.remove(at: list.count - 1)
} else {
list.append(char)
}
}
return list.isEmpty
}
}