String Reverse Preserving White Spaces in Java

String reversal is a common programming problem where a given string needs to be reversed such that the last character of the string becomes the first character, and vice versa. However, when preserving white spaces, the order of the white spaces should be maintained in the reversed string.

Approach: Reverse string preserving spaces.

Reverse string preserving spaces is a string manipulation problem where the goal is to reverse a given string while preserving the position of spaces within the string.

The steps to find the solution is mentioned below:

Step 1: Get the length of the input string "str".

Step 2: Create a character array called "result" with the same length as "str".

Step 3: Iterate over the string "str" and copy all non-space characters into the "result" array at their respective positions.

Step 4: Iterate over the string "str" again and copy all space characters into the "result" array at their respective positions.

Step 5: Reverse the "result" array by iterating over it from both ends and swapping each character with its corresponding character on the opposite end.

Step 6: Convert the "result" array to a string using the String constructor that takes a character array argument.

Step 7: Return the resulting reversed string.

Implementation

Here is an approach of how to reverse a string while preserving spaces.:

Filename: ReverseStringPreservingSpaces1.java

Output:

public class ReverseStringPreservingSpaces1 {
    public static void main(String[] args) {
        String str = "Hello   World!";
        String reversed = reverseStringPreservingSpaces(str);
        System.out.println(reversed);
    }    
    public static String reverseStringPreservingSpaces(String str) {
        int len = str.length();
        char[] result = new char[len];       
        // Iterate over the string and copy non-space characters into the result array
        for (int i = 0; i < len; i++) {
            if (str.charAt(i) != ' ') {
                result[i] = str.charAt(i);
            }
        }      
        // Iterate over the string again, this time copying spaces into the result array
        for (int i = 0; i < len; i++) {
            if (str.charAt(i) == ' ') {
                result[i] = ' ';
            }
        }
        // Reverse the result array
        for (int i = 0, j = len - 1; i < j; i++, j--) {
            char temp = result[i];
            result[i] = result[j];
            result[j] = temp;
        }        
        // Convert the result array to a string and return it
        return new String(result);
    }
}

Complexity analysis:

Time complexity: The first two for-loops iterate over the input string, each taking O(n) time, where n is the length of the input string. Therefore, the combined time complexity of the first two loops is O(n). The third for-loop that reverses the result array also takes O(n) time, as it iterates over half the length of the array. Finally, converting the result array to a string takes O(n) time. Therefore, the overall time complexity of the program is O(n).

Space complexity: The program creates a new character array with a length equal to the length of the input string, which takes O(n) space. Additionally, two integer variables are created for the third for-loop, which takes O(1) space. Therefore, the overall space complexity of the program is O(n).

Approach: Character Array with Two Pointers

Character Array with Two Pointers is an algorithmic technique used to manipulate character arrays by using two pointers that move towards each other from opposite ends of the array. The technique is particularly useful for solving problems involving string manipulation and can be used to efficiently reverse a string, check if a string is a palindrome, and remove duplicate characters from a string, among other things.

The steps to find the solution is mentioned below:

Step 1: Convert the input string into a character array using the toCharArray() method.

Step 2: Define two pointers for swapping characters, one at the beginning of the array (left) and the other at the end of the array (right).

Step 3: Iterate over the array using a while loop until the left and right pointers meet:

  • If the characters at the left and right pointers are both spaces, simply swap them and move both pointers inward one step.
  • If the character at the left pointer is a space, move the left pointer to the right one step.
  • If the character at the right pointer is a space, move the right pointer to the left one step.
  • If neither character is a space, swap them and move both pointers inward one step.

Step 4: Convert the character array back to a string using the String constructor that takes a character array as input.

Step 5: Return the reversed string as the output.

Implementation

Here is a possible implementation of the approach in Java, with comments explaining each step:

Filename: StringReversePreservingSpaces2.java

Output:

!dlroW olleH

Complexity Analysis:

Time Complexity The while loop in the reverseStringPreservingSpaces method has a linear time complexity of O(n), where n is the length of the input string. The reason for this is that the loop goes through the character array until the two pointers converge in the middle, which requires a maximum of n/2 iterations. Within each iteration, the algorithm checks the characters at the two pointers and swaps them if necessary. Since each character is checked at most once and swapped at most once, the time complexity of each iteration is O(1). Therefore, the total time complexity of the while loop is O(n * 1) = O(n).

Space Complexity: The space complexity of the algorithm is O(n), since the input string is converted to a character array of length n. The auxiliary space used by the algorithm for the pointers and temporary variables is O(1), which is constant.






Latest Courses