Algorithm weak, an algorithm every day, break through their own

The title

Write a function to reverse the input string, using no extra space in the form of the input string char[]. Modify the input array in place, using O(1) extra space

Example 1:

Input:"h"."e"."l"."l"."o"] output: ["o"."l"."l"."e"."h"]
Copy the code

Example 2:

Input:"H"."a"."n"."n"."a"."h"] output: ["h"."a"."n"."n"."a"."H"]
Copy the code

parsing

Use dual Pointers to swap in pairs

Reference code

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

    while (i < j) {
        lettemp = s[i]; s[i] = s[j]; s[j] = temp; i++; j--; }};Copy the code