-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.kt
87 lines (76 loc) · 2.03 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
sealed class Node {
abstract fun evaluate(): String
data class Word(private val inner: String) : Node() {
override fun evaluate(): String = inner.reversed()
}
data class Raw(private val inner: String) : Node() {
override fun evaluate(): String = inner
}
}
enum class Type {
TAG_OPENED,
TEXT,
WHITESPACE,
UNSET
}
fun parse(text: String): List<Node> {
val result = mutableListOf<Node>()
val builder = StringBuilder()
var type = Type.UNSET
fun createNode(f: (String) -> Node) {
result += f(builder.toString())
builder.clear()
type = Type.UNSET
}
var i = 0
fun peek(): Char? = text.getOrNull(i)
fun next() {
builder.append(text[i])
i += 1
}
loop@ while(true) {
val ch = peek()
when (type) {
Type.TAG_OPENED -> {
next()
if (ch != '>' && ch != null) {
continue@loop
}
createNode(Node::Raw)
}
Type.TEXT -> {
if (ch in 'a'..'z' || ch in '0'..'9' && ch != null) {
next()
continue@loop
}
createNode(Node::Word)
}
Type.WHITESPACE -> {
if (ch == ' ') {
next()
continue@loop
}
createNode(Node::Raw)
}
Type.UNSET -> {
if (ch == null) {
break@loop
}
next()
type = when (ch) {
'<' -> Type.TAG_OPENED
in 'a'..'z', in '0'..'9' -> Type.TEXT
' ' -> Type.WHITESPACE
else -> throw Error("NEVER")
}
}
}
if (ch == null) {
break
}
}
return result
}
fun main(args: Array<out String>) {
parse(readLine() ?: "").joinToString("") { it.evaluate() }.let(::println)
}