344. Reverse String
Problem
Tags: Two Pointers
, String
, Recursion
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"]
Constraints:
1 <= s.length <= 10^5
s[i]
is a printable ascii character.
Code
C
// 344. Reverse String (10/26/54217)
// Runtime: 48 ms (88.76%) Memory: 12.32 MB (38.80%)
void reverseString (char* s, int size) {
int half = size / 2;
int last = size - 1;
for (int i = 0; i < half; i++) {
char tmp = s[i];
s[i] = s[last - i];
s[last - i] = tmp;
}
}
JS
// 344. Reverse String (4/1/53720)
// Runtime: 127 ms (39.44%) Memory: 46.52 MB (94.82%)
/**
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
function reverseString(s) {
for (let i = 0; i < parseInt(s.length / 2); i++) [s[i], s[s.length - 1 - i]] = [s[s.length - 1 - i], s[i]];
}
RS
// 344. Reverse String (11/12/54217)
// Runtime: 17 ms (53.48%) Memory: 5.39 MB (93.97%)
impl Solution {
pub fn reverse_string(s: &mut Vec<char>) {
s.reverse();
}
}