![]() |
VOOZH | about |
Given string str, the task is to write a Java program to swap the first and the last character of the given string and print the modified string.
Examples:
Input: str = "GeeksForGeeks"
Output: seeksForGeekG
Explanation: The first character of the given string is 'G' and the last character of the given string is 's'. We swap the character 'G and 's' and print the modified string.Input: str = "Java"
Output: aavJ
Explanation: The first character of the given string is 'J' and the last character of the given string is 'a'. We swap the character 'J and 'a' and print the modified string.
Method 1 - using String.toCharArray() method
Below is the implementation of the above approach:
seeksForGeekG
Time Complexity: O(N)
Auxiliary Space: O(N)
Method 2 - using StringBuilder.setCharAt() method:
Below is the implementation of the above approach:
seeksForGeekG
Time Complexity: O(N)
Auxiliary Space: O(N) it is using extra space for StringBuilder sb
Method 3 - using String.substring() method
Below is the implementation of the above approach:
seeksForGeekG
Time Complexity: O(N)
Auxiliary Space: O(1)