-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBOJ_괄호의값.swift
62 lines (58 loc) · 1.7 KB
/
BOJ_괄호의값.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// 괄호 검사
import Foundation
let str = readLine()!
var stack: [String] = []
for c in str {
if c == "(" || c == "[" {
stack.append(String(c))
} else if c == ")" {
if stack.isEmpty { print(0); exit(0) }
else if stack.last! == "(" {
stack.removeLast()
var x = 2
while !stack.isEmpty, let n = Int(stack.last!) {
x += n
stack.removeLast()
}
stack.append(String(x))
} else if (stack.count >= 2 && stack[stack.count-2] == "("), let n = Int(stack.last!) {
stack.removeLast()
stack.removeLast()
var x = n*2
while !stack.isEmpty, let n = Int(stack.last!) {
x += n
stack.removeLast()
}
stack.append(String(x))
} else {
print(0); exit(0)
}
} else if c == "]" {
if stack.isEmpty { print(0); exit(0) }
else if stack.last! == "[" {
stack.removeLast()
var x = 3
while !stack.isEmpty, let n = Int(stack.last!) {
x += n
stack.removeLast()
}
stack.append(String(x))
} else if (stack.count >= 2 && stack[stack.count-2] == "["), let n = Int(stack.last!) {
stack.removeLast()
stack.removeLast()
var x = n*3
while !stack.isEmpty, let n = Int(stack.last!) {
x += n
stack.removeLast()
}
stack.append(String(x))
} else {
print(0); exit(0)
}
}
}
if stack.count == 1, let n = Int(stack.last!) {
print(n)
} else {
print(0)
}