Question:

Write a function that takes a string as input and returns the string reversed.

Example:

  1. Input: "hello"
  2. Output: "olleh"
Input: "A man, a plan, a canal: Panama"
Output: "amanaP :lanac a ,nalp a ,nam A"

Solution:

/**
 * @param {string} s
 * @return {string}
 */
var reverseString = function(s) {
  let arr = s.split('');
  let temp;
  let len = arr.length;

  for (let i = 0; i < len/2; i++) {
    //交换首尾
    temp = arr[i];
    arr[i] = arr[len-1-i];
    arr[len-1-i] = temp;
  }

  return arr.join('')
};

Runtime: 76 ms, faster than 52.15% of JavaScript online submissions for Reverse String