Skip to content

Instantly share code, notes, and snippets.

@Husseinhj
Last active August 8, 2022 10:28
Show Gist options
  • Save Husseinhj/daf42c5f0b99e9b100820fdcb65c07b2 to your computer and use it in GitHub Desktop.
Save Husseinhj/daf42c5f0b99e9b100820fdcb65c07b2 to your computer and use it in GitHub Desktop.
Some way to reverse string chars by using Kotlin language
/**
* Kotlin code challenges. Find related objects
* playgound: https://pl.kotl.in/NvjzuL7se
*/
import java.util.*
import kotlin.collections.ArrayList
fun main() {
val message = "Hello, world!"
println("Original: $message \n")
println("1) ${kotlinReverse(message)}")
println("2) ${String(optimisedArrayReverse(message.toCharArray()))}")
println("3) ${String(arrayReverseByStack(message.toCharArray()))}")
}
fun kotlinReverse(sentence: String): String {
return sentence.reversed()
}
fun arrayReverseByStack(chars: CharArray): CharArray {
val length = chars.size - 1
val stackChars = Stack<Char>()
val reversedList: ArrayList<Char> = arrayListOf()
for (char in chars) {
stackChars.push(char)
}
while (!stackChars.empty()) {
reversedList.add(stackChars.pop())
}
return reversedList.toCharArray()
}
fun optimisedArrayReverse(chars: CharArray): CharArray {
val reversedChars = chars
val length = chars.size
val center = (length / 2) - 1
var reversedIndex = chars.lastIndex
if (center < 0) {
return reversedChars
}
for (index in 0..center) {
val temp = reversedChars[index]
reversedChars[index] = chars[reversedIndex]
reversedChars[reversedIndex] = temp
reversedIndex -= 1
}
return reversedChars
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment