-
Notifications
You must be signed in to change notification settings - Fork 0
/
001.swift
47 lines (39 loc) · 1.01 KB
/
001.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
func isBracketStringBalanced(_ string: String) -> Bool {
var stack = ""
for char in string {
switch char {
case "(", "{", "[":
stack.append(char)
case ")":
guard stack.last == "(" else { return false }
stack.removeLast()
case "}":
guard stack.last == "{" else { return false }
stack.removeLast()
case "]":
guard stack.last == "[" else { return false }
stack.removeLast()
default: return false
}
}
return stack.isEmpty
}
func runTests() {
assert(isBracketStringBalanced("([])[]({})") == true)
assert(isBracketStringBalanced("([)]") == false)
assert(isBracketStringBalanced("((()") == false)
print("Tests passed.")
}
func runInteractive() {
while true {
if let line = readLine() {
let isBalanced = isBracketStringBalanced(line)
print(isBalanced)
}
}
}
func main() {
runTests()
runInteractive()
}
main()