static void reverseString(String input) {
char[] inputArray = input.toCharArray();
char[] result = new char[inputArray.length];
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] == ' ') {
result[i] = ' ';
}
}
int j = result.length - 1;
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] != ' ') {
if (result[j] == ' ') {
j--;
}
result[j] = inputArray[i];
j--;
}
}
System.out.println(input + " --> " + String.valueOf(result));
}
CAn some one explain how the both for loop works, getting confused. Else any other optimized code ?
The first for loop stores space in the result array for the corresponding space in the input array i.e., in order to preserve the space, wherever there is a space in the input array the first for loop stores a space in the result array at the same index position.
Since the spaces are already stored the, rest of the string is reversed in the second loop.
The spaces that are present in the input array are ignored in the second loop using the if statement. And while reversing get if it encounters a space in the result array, it moves to the next index position to store the remaining string in reverse order by decrementing the value of j and incrementing the value of i.