Created
February 12, 2019 01:26
-
-
Save hkurokawa/400da9cd2cd30442634e40bbf04c8565 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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