Reverse a string using a stack in Kotlin

To reverse a string using a stack, you can follow these steps:

  1. Create an empty stack.
  2. Push each character of the string onto the stack, one by one, in the order they appear in the string.
  3. Pop each character from the stack, one by one, and append it to a new string.
  4. Return the new string.

Kotlin code to reverse a string using a stack:

Kotlin
import kotlin.collections.ArrayDeque

fun reverseStringUsingStack(input: String): String {
    val stack = ArrayDeque<Char>()
    input.forEach { stack.addLast(it) }
    val result = StringBuilder()
    while (!stack.isEmpty()) {
        result.append(stack.removeLast())
    }
    return result.toString()
}

fun main() {
    val input = "edoCniltoK"
    val reversed = reverseStringUsingStack(input)
    println("Input string: $input")
    println("Reversed string: $reversed")
}

we use an ArrayDeque as our stack, which we initialize to be empty. We then iterate through the characters of the input string using the forEach function, and push each character onto the stack using the push function.

Next, we create a StringBuilder object to hold the reversed string, and use a while loop to pop each character from the stack using the pop function and append it to the StringBuilder using the append function.

Finally, we convert the StringBuilder to a string using the toString function and return the reversed string.

we define a main function that initializes an input string to be “Hello, world!”. We then call the reverseStringUsingStack function on the input string to get the reversed string, which we store in the reversed variable.

Finally, we use println to print both the original input string and the reversed string to the console, separated by a newline.

The time complexity of the above code is O(n), where n is the length of the input string. This is because we iterate through each character in the input string once, and perform a constant amount of work for each character (i.e., pushing it onto the stack). We then iterate through the stack once, popping each character off and appending it to the result string, which also takes O(n) time.

The space complexity of the above code is also O(n), where n is the length of the input string. This is because we use a stack to store each character in the input string, which takes O(n) space. We also use a StringBuilder to store the reversed string, which takes O(n) space in the worst case (when the input string is itself a palindrome).

Leave a Comment