String: Program to reverse a string


Strings are Immutable in Java and its value cannot be changed.

 

What does it mean that String is Immutable in Java?

In java, you cannot change/update a string once it is defined. Any modification to the original string will result in a new string object.
Below code is not possible in java but is possible in many other languages eg. C/C++
Eg:
String name = “Fun”;
name[0] = 'S';

In order to reverse a string, we will use a data structure that supports mutability
For that we use the StringBuilder Class as it is mutable.

 

Algorithm

  1. Store the index of the first and last element in the variable low and high respectively
  2. While low < high
    • Swap the characters at string low and string high
  3. Return the string

 

Complexity

Time Complexity: O(N)
Space Complexity: O(1)

The Time Complexity is O(N) as it takes N/2 iterations
and the Space Complexity is Constant as the space of StringBuilder is not considered because
the algorithm requires a mutable version of String.

 

Java Code
class StringOperations {
        public static String reverseString(String givenString) {
          // Converting the string to StringBuilder
          StringBuilder builderString = new StringBuilder(givenString);
        
          int low = 0, high = givenString.length() - 1;
          // Iterating through elements and swapping the both ends
          while (low < high) {
            char temp = builderString.charAt(low);
            builderString.setCharAt(low, builderString.charAt(high));
            builderString.setCharAt(high, temp);
        
            low++;
            high--;
          }
        
          // Converting StringBuilder to string
          return builderString.toString();
        }
        
        public static void main(String[] args) {
          String givenString1 = "FunDesk";
          String resultString1 = reverseString(givenString1);
        
          System.out.println("Given String: " + givenString1);
          System.out.println("Reversed String: " + resultString1);
          System.out.println();
        
          // Let's Reverse another String
          String givenString2 = "Hello World!";
          String resultString2 = reverseString(givenString2);
        
          System.out.println("Given String: " + givenString2);
          System.out.println("Reversed String: " + resultString2);
          System.out.println();
        }
 }

 

Output

Given String: FunDesk
Reversed String: kseDnuF

Given String: Hello World!
Reversed String: !dlroW olleH



Thanks for feedback.



Read More....
Check if a string is a valid palindrome
Check if two strings are anagram of each other
Count the occurrence of chars in a given string
Find duplicate chars in a String
First non-repeating character in String