The problem is to reverse a given string in place. The function should do this without using any extra space for another array (modifying the input array directly is required).
Leetcode Problem Number: 344
Given a character array s
, reverse the array.
Input: ['h', 'e', 'l', 'l', 'o']
Output: ['o', 'l', 'l', 'e', 'h']
To reverse the string in place, we can use the two-pointer technique:
left
) at the beginning of the array and the other (right
) at the end of the array.left
pointer one step to the right and the right
pointer one step to the left.left
is greater than or equal to right
.This approach ensures we process each character only once and swap them in place without using any extra space.
Here’s the Java implementation of the above strategy:
public class Solution {
public void reverseString(char[] s) {
int left = 0;
int right = s.length - 1;
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
This code defines a class Solution
with a method reverseString
that takes a character array s
as input and reverses it in place.
The while
loop continues until the left
pointer is no longer less than the right
pointer, ensuring that we swap elements from the outside towards the center of the array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?