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
- Store the index of the first and last element in the variable low and high respectively
- While low < high
- Swap the characters at string low and string high
- 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