Inversion algorithm leetcode 344. distal end of the string

# Front end of the algorithm leetcode 344. reversal string

Title Description

Write a function, its role is to input string reversed. Input string to a character array char [] given in the form.

Do not allocate additional space to another array, you must place modify the input array, use the extra space O (1) solution to this problem.

You may assume that all the characters in the array are the ASCII table printable characters.

 

Example 1:

输入:["h","e","l","l","o"]
输出:["o","l","l","e","h"]

Example 2:

输入:["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]

344. reversal string

Overview

With s.reverse () The shoes do not arrogant, the project can do so, but the algorithm in question does not recommend this Ha

prompt

Double pointer, recursive

Resolve

Solution one: the double pointer

Define two pointers head and tail, as long as they do not coincide exchanged character pointer

Solution II: recursive

Take half of the length of the string, the string then begins to switch from the intermediate, until the initial value of 0

algorithm

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function (s) {
  // 双指针
  if (s.length > 0) {
    let [i, j] = [0, s.length - 1];
    while (i < j) {
      [s[i], s[j]] = [s[j], s[i]];
      i++;
      j--;
    }
  }
  // 递归
  // const swap = (start, s) => {
  //   if (start > 0) {
  //     [s[start - 1], s[s.length - start]] = [s[s.length - start], s[start - 1]];
  //     swap(--start, s);
  //   }
  // };
  // swap(~~(s.length / 2), s);
};

Incoming operating results of test cases

input:['h', 'e', 'l', 'l', 'o']
output:[ 'o', 'l', 'l', 'e', 'h' ]

Results of the

执行用时 :120 ms, 在所有 javascript 提交中击败了98.62%的用户
内存消耗 :47.3 MB, 在所有 javascript 提交中击败了10.98%
的用户

GitHub repository

344. reversal string

Guess you like

Origin www.cnblogs.com/moshuying/p/11871310.html