Skip to content

Instantly share code, notes, and snippets.

@brunofarache
Last active November 20, 2020 01:36
Show Gist options
  • Save brunofarache/105d3fc39e68b00f58fc3a6b592d525c to your computer and use it in GitHub Desktop.
Save brunofarache/105d3fc39e68b00f58fc3a6b592d525c to your computer and use it in GitHub Desktop.
def findLettersOrDigits(chars: Array[Char], i: Int, f: Char => Boolean): String = {
if (i == chars.length) return ""
val char = chars(i)
if (f(char)) {
char.toString + findLettersOrDigits(chars, i + 1, f)
}
else {
""
}
}
def findCloseBracket(chars: Array[Char], i: Int, count: Int): Int = {
if (count == 0) return i - 1
if (chars(i) == '[') {
findCloseBracket(chars, i + 1, count + 1)
}
else if (chars(i) == ']') {
findCloseBracket(chars, i + 1, count - 1)
}
else {
findCloseBracket(chars, i + 1, count)
}
}
def decodeString(s: String): String = {
def decode(chars: Array[Char], i: Int): String = {
if (i >= chars.length) return ""
val char = chars(i)
if (char.isLetter) {
val letters = findLettersOrDigits(chars, i, _.isLetter)
letters + decode(chars, i + letters.length)
}
else {
val repeat = findLettersOrDigits(chars, i, _.isDigit)
val last = findCloseBracket(chars, i + repeat.length + 1, 1)
val repeated = decodeString(s.substring(i + repeat.length + 1, last)) * repeat.toInt
repeated + decode(chars, last + 1)
}
}
decode(s.toCharArray, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment