Skip to content

Instantly share code, notes, and snippets.

@ktprezes
Created May 1, 2023 09:58
Show Gist options
  • Save ktprezes/3685bc44f11437c5a9b984a2f48c44f6 to your computer and use it in GitHub Desktop.
Save ktprezes/3685bc44f11437c5a9b984a2f48c44f6 to your computer and use it in GitHub Desktop.
kotlin - palindrome test - 3 implementations: string reversed, stack, stack with size optimized
import kotlin.collections.ArrayDeque
// version #1 - the shortest implementation
// fun checkPalindrome(word: String): Boolean = word.reversed() == word
// version #2 - 'pure stack' implementation
/*
fun checkPalindrome(word: String): Boolean {
if (word.isBlank())
return false
val stack: ArrayDeque<Char> = ArrayDeque(word.length)
word.forEach(stack::addFirst)
word.forEach {
if (it != stack.removeFirst())
return false
}
return true
}
*/
// version #3 - stack implementation with stack size optimization
fun checkPalindrome(word: String): Boolean {
if (word.isBlank()) return false
val wordHalfLen: Int = word.length / 2 + word.length % 2
val word2ndHalfStartIndx = word.length - wordHalfLen
val stack: ArrayDeque<Char> = ArrayDeque(wordHalfLen)
word.forEachIndexed { i, c ->
// only 1st half of the word is pushed on the stack
if (i < wordHalfLen) {
stack.addFirst(c)
}
// and the 2nd half is compared against the stack
if (i >= word2ndHalfStartIndx && c != stack.removeFirst()) {
return false
}
}
return true
}
fun main() {
val input = readln()
println(checkPalindrome(input))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment