Recall that String is immutable, so for modifications we have to first convert it to CharArray. Array is mutable, so we can perform in-place swapping in order to reverse it. In-place means we modify the same CharArray using swaps and need not create any new CharArray.
Algorithm
Algorithm
To reverse an array, we can swap the first half elements of the array with the second half elements of the array. First element from start will be swapped with first element from the end, second element from the start will be swapped with second element from the end, so on and so forth. This way for an array of n
elements, we have to perform n/2
iterations and on each iteration, we swap i
th element with (n-1-i)
^^th^^ element.
Implementation
Implementation
fun String.reversedUsingSwap(): String {
val array = toCharArray()
for (i in 0 until (array.size / 2)) {
array[i] = array[array.lastIndex - i].apply {
array[array.lastIndex - i] = array[i]
}
}
return array.concatToString()
}
This works for both even and odd lengths of string. For example,
- if length is
2
(even), we perform2/2 = 1
iteration i.e.0 until 1
- if length is
5
(odd), we perform5/2 = 2
iteration i.e.0 until 2