Skip to content

Instantly share code, notes, and snippets.

@hkurokawa
Created February 12, 2019 01:26
Show Gist options
  • Save hkurokawa/400da9cd2cd30442634e40bbf04c8565 to your computer and use it in GitHub Desktop.
Save hkurokawa/400da9cd2cd30442634e40bbf04c8565 to your computer and use it in GitHub Desktop.
import java.util.Stack
fun parse(s: String): MutableList<Any> {
val stack = Stack<MutableList<Any>>()
stack.add(mutableListOf())
var i = 0
while (i < s.length) {
val ch = s[i]
when (ch) {
'[' -> stack.push(mutableListOf())
']' -> stack.pop().also { stack.peek().add(it) }
else ->
if (ch in '0'..'9') {
var j = i
while (s[j] in '0'..'9') j++
stack.peek().add(s.substring(i until j).toInt())
i = j - 1
}
}
i++
}
return stack.pop()
}
fun main(args: Array<String>) {
val list = parse("[1, 2, [3], [4, [5, 6], []]]")
println(list)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment