344. Reverse String Easy
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.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Approach
Input: A character list s, representing the original string. It requires an in-place reverse.
Output: Reverse the order of characters, modifying the input list s directly without returning a new value.
This is a classic opposite-direction two pointers problem.
We can define two pointers: left = 0, right = len(s) - 1, pointing to the start and the end of the string respectively.
Then perform the following operations:
- While
left < right, constantly swaps[left]ands[right]; - After each swap, move
leftone step to the right, and moverightone step to the left; - When the two pointers meet or cross, it implies the entire string has been completely reversed.
Implementation
python
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left, right = 0, len(s) - 1
# Swap left and right characters while the left pointer is less than the right pointer
while left < right:
# Use Python's swap syntax, omitting the temporary variable
s[left], s[right] = s[right], s[left]
# Pointers move towards each other
left += 1
right -= 1javascript
/**
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
const reverseString = function(s) {
let left = 0;
let right = s.length - 1;
while (left < right) {
const temp = s[left];
s[left] = s[right];
s[right] = temp;
left ++;
right --;
}
};Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)