344. Reverse String

Description

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

Example:
Given s = "hello", return "olleh".

Solution

Solution 1

/**
 * @param {string} s
 * @return {string}
 */
var reverseString = function(s) {
    "use strict";
    let result = "";
    for (let i = s.length-1; i >= 0; i--) {
        result += s[i];
    }
    return result;
};

Solution 2

/**
 * Use two pointers to reverse the original string
 * note that JavaScript Strings are immutable
 * thus we need to convert the original string into an array first
 * @param {string} s
 * @return {string}
 */
var reverseString = function(s) {
    "use strict";
    s = s.split("");
    for (let i = 0, j = s.length-1; i < Math.ceil(s.length/2); i++, j--) {
        let tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
    }
    return s.join("");
};

results matching ""

    No results matching ""