Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in-place with O(1) extra memory.

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Constraints:

Contents

In this approach, we will use two pointers to point to both ends of input string s and swap characters.

Implementation steps:
import java.util.Arrays; public class ReverseString { static void reverseString(char[] s) { int i = 0; int j = s.length-1; while(i<j) { char temp = s[i]; s[i] = s[j]; s[j] = temp; i++; j--; } } public static void main(String[] args) { char[] s = new char[]{'h', 'e', 'l', 'l', 'o'}; reverseString(s); System.out.println(Arrays.toString(s)); s = new char[]{'H', 'a', 'n', 'n', 'a', 'h'}; reverseString(s); System.out.println(Arrays.toString(s)); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of the input array s.
Space complexity: O(1).

Above implementations source code can be found at GitHub link for Java code