Most Efficient Way to Reverse String In Java

AnanthaRamu MP
0

Most Efficient Way to Reverse String In Java


Courtesy: Shiksha

Hey there! Reversing a string efficiently in Java without `StringBuffer` or `StringBuilder` is a great way to learn about manipulating data.

Let's break it down. Imagine your string as a word, say "hello". You want to turn it into "olleh".

The trick here is to think of the string as an array of characters. You can swap characters from start and finish until you meet in the middle.


Here’s how you can do it step-by-step:


  • Convert to Character Array: First, you'll convert your `String` into a `char` array. This is because `String` objects in Java are immutable, meaning you can't change individual characters once the string is created. A `char` array, on the other hand, is mutable.String originalString = "hello";


char[] charArray = originalString.toCharArray();


  • Two Pointers: Now, you'll need two "pointers" (variables that represent indices). One pointer will start at the beginning of the array (`left`), and the other at the end (`right`).int left = 0;


int right = charArray.length - 1;


  • Swap and Move: You'll loop as long as `left` is less than `right`. Inside the loop:
    • Swap the characters at the `left` and `right` positions.
    • Increment `left` (move it one step to the right).
    • Decrement `right` (move it one step to the left).


while (left < right) {
    // Swap characters
    char temp = charArray[left];
    charArray[left] = charArray[right];
    charArray[right] = temp;
    // Move pointers
    left++;
    right--;
 }

Let's trace it with "hello":

  • Initial: `h e l l o` (`left=0`, `right=4`)
  • Swap `h` and `o`: `o e l l h` (`left=1`, `right=3`)
  • Swap `e` and `l`: `o l l e h` (`left=2`, `right=2`)

The loop stops because `left` is no longer less than `right`.

  • Convert Back to String: Finally, convert the modified `char` array back into a `String`.String reversedString = new String(charArray);

Putting it all together in a method:


public class StringReverser {

    public static String reverseString(String str) {

        if (str == null || str.isEmpty()) {
            return;
        }

        char[] charArray = str.toCharArray();
        int left = 0;
        int right = charArray.length - 1;
        while (left < right) {
            // Swap characters
            char temp = charArray[left];
            charArray[left] = charArray[right];
            charArray[right] = temp;
            // Move pointers
            left++;
            right--;
        }
        return new String(charArray);
    }


    public static void main(String[] args) {
        
        String original1 = "hello";
        String reversed1 = reverseString(original1);
        System.out.println("Original: " + original1 + ", Reversed: " + reversed1); 
        // Output: Original: hello, Reversed: olleh
        
        String original2 = "programming";
        String reversed2 = reverseString(original2);
        System.out.println("Original: " + original2 + ", Reversed: " + reversed2); 
        // Output: Original: programming, Reversed: gnimmargorp
        
        String original3 = "a";
        String reversed3 = reverseString(original3);
        System.out.println("Original: " + original3 + ", Reversed: " + reversed3); 
        // Output: Original: a, Reversed: a

        String original4 = "";
        String reversed4 = reverseString(original4);
        System.out.println("Original: '" + original4 + "', Reversed: '" + reversed4 + "'"); 
        // Output: Original: '', Reversed: ''

        String original5 = null;
        String reversed5 = reverseString(original5);
        System.out.println("Original: " + original5 + ", Reversed: " + reversed5); 
        // Output: Original: null, Reversed: null
    }

}


Why is this efficient?


Time Complexity: O(n)

We iterate through about half of the string's length (n/2) to perform swaps. In terms of big O notation, this is considered linear time, which is very good.


Space Complexity: O(n)

We create a `char` array that is the same size as the original string. This is also considered linear space.

This method is commonly taught in DSA because it effectively demonstrates in-place modification and the use of pointers, which are fundamental concepts.


Let me know if you want to try another example or have any questions! Keep up the great work learning programming!



Post a Comment

0 Comments

No SPAMS please.Give constructive Feedbacks.

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Ok, Go it!