Skip to content

Instantly share code, notes, and snippets.

@saem
Last active February 10, 2019 03:24
Show Gist options
  • Select an option

  • Save saem/48990c19a09f74ccac2f439ebfbeaddf to your computer and use it in GitHub Desktop.

Select an option

Save saem/48990c19a09f74ccac2f439ebfbeaddf to your computer and use it in GitHub Desktop.
Use a kotlin scratchpad for this or write a quick main
fun nonRepeating(string: String): Int {
return when (string.length) {
0 -> 0
1 -> 1
else -> nonRepeatingActual(string, 0, 1)
}
}
fun nonRepeatingActual(
string: String,
currentRun: Int,
longest: Int,
seen: Set<Char> = emptySet()
): Int {
if (string.isEmpty()) {
return maxOf(currentRun, longest)
}
val subStr = string.substring(1)
val newRunLength = if (seen.contains(string.first())) {
currentRun
} else {
nonRepeatingActual(
subStr,
currentRun + 1,
maxOf(currentRun + 1, longest),
seen + string[0]
)
}
val isThisANewStart = if (subStr.length > longest) {
nonRepeatingActual(subStr, 1, longest, setOf(string.first()))
} else {
0
}
return maxOf(newRunLength, longest, isThisANewStart)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment