Skip to content

Instantly share code, notes, and snippets.

@Husseinhj
Last active August 8, 2022 10:28
Show Gist options
  • Save Husseinhj/76eaae597c399617abf9b68139aecdfe to your computer and use it in GitHub Desktop.
Save Husseinhj/76eaae597c399617abf9b68139aecdfe to your computer and use it in GitHub Desktop.
Reverse words
/**
* Kotlin code challenges. Find related objects
* playground: https://pl.kotl.in/x4pqB-guK
*/
import java.util.*
import kotlin.collections.ArrayList
fun main() {
val message = "Hello, world!"
println("Original: $message \n")
println("1) ${reverseWords(message)}")
println("2) ${optimizeReverseWords(message)}")
println("3) ${reverseWordsByStack(message)}")
}
fun reverseWords(sentence: String): String {
val words = sentence.split(" ")
return words.reversed().joinToString(" ")
}
fun reverseWordsByStack(sentence: String): String {
val words = sentence.split(" ")
val wordStack: Stack<String> = Stack()
val reversedWords: ArrayList<String> = arrayListOf()
for (word in words) {
wordStack.push(word)
}
while(!wordStack.empty()) {
reversedWords.add(wordStack.pop())
}
return reversedWords.joinToString(" ")
}
fun optimizeReverseWords(sentence: String): String {
val words = sentence.split(" ").toTypedArray()
val length = words.size
val center = (length / 2) - 1
var lastIndex = words.lastIndex
if (center < 0) {
return sentence
}
for (index in 0..center) {
words[lastIndex] = words[index].also { words[index] = words[lastIndex] }
lastIndex -= 1
}
return words.joinToString(" ")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment