Last active
November 20, 2020 01:36
-
-
Save brunofarache/105d3fc39e68b00f58fc3a6b592d525c to your computer and use it in GitHub Desktop.
This file contains 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
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