Reverse String

Write a function to reverse the input string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must modify the input array in-place with O(1) extra memory.
You may assume that all the characters in the array are printable ASCII characters.

Example

Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"]
Input: ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"]

Solution

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function(s) {
    var n = s.length;
    for(let i=0; i<n/2; ++i){
        [s[i], s[n-i-1]] = [s[n-i-1], s[i]];
    }
    return void 0;
};

Idea

For the in-place reverse of an array, we can directly reverse it based on the index. First, define n as the length of the array, and then define a loop. Since we only need to swap N/2 times, we set the termination condition to n/2. Then, use the destructuring assignment defined by the ES6 standard to directly swap the values of the index positions of the array traversal loop and the i-th index position from the end to the front. The problem requires an in-place reverse, so just return void 0.

Daily Question

https://github.com/WindrunnerMax/EveryDay

Reference

https://leetcode-cn.com/problems/reverse-string