-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.kt
101 lines (91 loc) · 2.49 KB
/
solution.kt
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
sealed class Node {
abstract fun evaluate(): Int
data class RoundBracket(val child: Node) : Node() {
override fun evaluate(): Int = 2 * child.evaluate()
}
data class SquareBracket(val child: Node) : Node() {
override fun evaluate(): Int = 3 * child.evaluate()
}
data class BracketSequence(val children: List<Node>) : Node() {
override fun evaluate(): Int =
children.sumBy { it.evaluate() }
}
object None : Node() {
override fun evaluate(): Int = 1
}
object Error : Node() {
override fun evaluate(): Int = 0
}
}
class Parser(private val source: String) {
private var index = 0
private fun peek(): Char? =
if (hasNext()) {
source[index]
} else {
null
}
private fun next(): Char? =
if (hasNext()) {
val result = source[index]
index += 1
result
} else {
null
}
private fun hasNext(): Boolean = index < source.length
fun parse(): Node {
val result = nextBracketSequence()
if (hasNext()) {
return Node.Error
} else {
return result
}
}
fun nextBracketSequence(): Node {
val nodeList = mutableListOf<Node>()
loop@ while (hasNext()) {
val current = when (peek()) {
'(' -> nextRoundBracket()
'[' -> nextSquareBracket()
else -> {
if (nodeList.isEmpty()) {
return Node.None
} else {
break@loop
}
}
}
if (current == Node.Error) {
return Node.Error
}
nodeList.add(current)
}
return Node.BracketSequence(nodeList)
}
fun nextRoundBracket(): Node {
next()
val inner = nextBracketSequence()
if (inner == Node.Error) {
return Node.Error
}
if (next() != ')') {
return Node.Error
}
return Node.RoundBracket(inner)
}
fun nextSquareBracket(): Node {
next()
val inner = nextBracketSequence()
if (inner == Node.Error) {
return Node.Error
}
if (next() != ']') {
return Node.Error
}
return Node.SquareBracket(inner)
}
}
fun main(args: Array<out String>) {
println(Parser(readLine()!!).parse().evaluate())
}