Reverse String
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)
Example 1
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Output: ["o","l","l","e","h"]
Example 2
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Output: ["h","a","n","n","a","H"]
Constraints:
1 <= s.length <= 105 is a printable ascii character.s[i]
Solution 1 - Swap characters from both sides using two pointers
In this approach, we will use two pointers to point to both ends of input string s
Implementation steps:
-
Create two pointer variables
andi to point to left and right ends of input stringj characters.s -
Then, run a
loop untilwhile andi don't intersect with each other, then swap the characters at these indexes, and increment left pointeri and decrement right pointeri .j
Java
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 ns
Space complexity: O(1).
Above implementations source code can be found at