Reverse String
Reverse an array of characters in place by swapping pairs from both ends toward the middle.
A string is given as an array of characters s
Example 1
Output: ["o", "l", "l", "e", "h"]
Example 2
Output: ["h", "a", "n", "n", "a", "H"]
The Idea
Think of five letter tiles in a row on a table, spelling h, e, l, l, o. To make them read backwards, you could take them all off and lay them down again from the other end. That needs a second row of space, though, and the problem gives us only the one row.
So look at where each tile has to end up. The h at the front belongs at the back, and the o at the back belongs at the front. Those two simply trade places. The e in second place and the l in second-to-last place trade places too. Counting positions from 0, as Java does, the character at position in - 1 - in
That raises the question of order and of when to stop. Look at the picture below. Two markers, lohi
In the row labelled "start", lohilohi
So reversing is a handful of swaps that work from the outside in, and it ends where the two markers meet. Two markers that start at opposite ends of an array and walk toward each other are usually called two pointers.
Solution Approach
Turning that idea into code means settling three things: how to swap two characters without losing one, when to stop, and why the easier ways that build a new string do not fit here.
Swapping two characters
How do we trade two characters inside one array? Writing s[hi]s[lo]lotmps[hi]
Where to stop
Why not simply run is[i]s[n - 1 - i]lo < hi
With an odd length, the markers meet on the middle character, which stays where it is. With an even length, such as H, a, n, n, a, h, they cross after the swap of the two n's, and the check stops the loop just the same.
Building a new string instead
For a Java Stringnew StringBuilder(s).reverse()s
Java Solution
The method reverseString
- First, put the marker
on position 0 and the markerlo on the last position,hi .s.length - 1 - Start a loop that runs while
is less thanlo .hi - Inside the loop, copy
intos[lo] , writetmp intos[hi] , and writes[lo] intotmp .s[hi] - Move
one step right andlo one step left, toward the middle.hi - When the loop ends, the array is reversed. The method returns nothing, because it changed the caller's array.
The main
import java.util.Arrays;
public class ReverseString {
public static void reverseString(char[] s) {
int lo = 0;
int hi = s.length - 1;
while (lo < hi) {
char tmp = s[lo]; // keep the left character before it is overwritten
s[lo] = s[hi];
s[hi] = tmp;
lo++; // both markers step toward the middle
hi--;
}
}
public static void main(String[] args) {
char[][] inputs = {
{'h', 'e', 'l', 'l', 'o'},
{'H', 'a', 'n', 'n', 'a', 'h'},
{'a', 'b'},
{'x'},
{}
};
for (char[] s : inputs) {
String before = Arrays.toString(s);
reverseString(s);
System.out.println(before + " -> " + Arrays.toString(s));
}
}
}
Running it prints:
[h, e, l, l, o] -> [o, l, l, e, h]
[H, a, n, n, a, h] -> [h, a, n, n, a, H]
[a, b] -> [b, a]
[x] -> [x]
[] -> []
The line for h, e, l, l, o matches the last row of the picture: two swaps, with the middle l left alone. In the line for H, a, n, n, a, h, the capital H moved from the front to the back, so case is kept as it is. [a, b][b, a]
The last two lines come back unchanged. For [x]hilohilo < hi
The original implementation,
Complexity
The loop does one swap per pair of characters and then stops in the middle.
- Time: O(n), because
andlo each walk only half of the n characters, giving n / 2 swaps of three assignments each.hi - Space: O(1), because the only extra memory is
,lo andhi , the same for an array of five characters or five million.tmp
The same swap loop, run on one part of an array at a time, reverses each word in