-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_20_Valid Parentheses .swift
More file actions
111 lines (98 loc) · 2.33 KB
/
leetcode_20_Valid Parentheses .swift
File metadata and controls
111 lines (98 loc) · 2.33 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//
// leetcode_20_Valid Parentheses .swift
// fight
//
// Created by 이재은 on 2020/11/25.
// Copyright © 2020 jaeeun. All rights reserved.
//
import Foundation
//LeetCode 20. Valid Parentheses
// 주어진 s의 괄호가 짝이 맞아 유효한지 무효한지 구하기
//Given a string s 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.
//
//
//Example 1:
//
//Input: s = "()"
//Output: true
//Example 2:
//
//Input: s = "()[]{}"
//Output: true
//Example 3:
//
//Input: s = "(]"
//Output: false
//Example 4:
//
//Input: s = "([)]"
//Output: false
//Example 5:
//
//Input: s = "{[]}"
//Output: true
//
//
//Constraints:
//
//1 <= s.length <= 10^4
//s consists of parentheses only '()[]{}'.
// 풀이 1
func isValid(_ s: String) -> Bool {
var parentheses = [String]()
if s.count % 2 != 0 { return false }
s.forEach {
switch $0 {
case ")":
if parentheses.last == "(" {
parentheses.removeLast()
} else {
parentheses.append(String($0))
}
case "]":
if parentheses.last == "[" {
parentheses.removeLast()
} else {
parentheses.append(String($0))
}
case "}":
if parentheses.last == "{" {
parentheses.removeLast()
} else {
parentheses.append(String($0))
}
default:
parentheses.append(String($0))
}
}
return parentheses.isEmpty
}
// 풀이 2
func isValid(_ s: String) -> Bool {
let parentheses = [")": "(", "]": "[", "}": "{"]
var stack = [String]()
for text in s {
if let openP = parentheses[String(text)] {
if stack.last == openP {
stack.removeLast()
} else {
return false
}
} else {
stack.append(String(text))
}
}
return stack.isEmpty
}
print(isValid("()")) // true
print(isValid("()[]{}")) // true
print(isValid("(]")) // false
print(isValid("([)]")) // false
print(isValid("{[]}")) // true
print(isValid("]")) // false
print(isValid(")(){}")) // false