LeetCode — 344. Reverse String
Reversing a string is a common problem in programming. It can be efficiently solved by using a simple two-pointer approach. This method is advantageous because it modifies the string in place without the need for additional memory for a new string.
Process
- Initialize Two Pointers: We start by initializing two pointers, left at the start of the array and right at the end.
- Swap Elements: We then enter a loop where we swap the elements at the left and right pointers.
- Move Pointers: After each swap, we move the left pointer one step forward and the right pointer one step backward.
- Loop Condition: This process continues until the left pointer is greater than or equal to the right pointer, indicating that the entire array has been reversed.
Time and Space Complexity
Time Complexity: The time complexity of this function is O(n), where n is the length of the string. Each element is swapped only once.
Space Complexity: The space complexity is O(1), as the reversal is done in place with no need for extra space.
JavaScript version
/**
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
var reverseString = function (s) {
let left = 0, right = s.length - 1;
while (left < right) {
let temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
};
Java version
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--;
}
}
}