344.reverse-string


描述

Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in-place with O(1) extra memory.

测试用例

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

题解

进行数组内的元素交换。

var reverseString = function(s) {
    let n = Math.floor(s.length / 2), l = s.length;
    for(let i = 0; i < n; i++) {
        let temp = s[i];
        s[i] = s[l - i - 1];
        s[l - i - 1] = temp;
    }
};

结果

Accepted

477/477 cases passed (168 ms)

Your runtime beats 15.06 % of javascript submissions

Your memory usage beats 5.18 % of javascript submissions (50.4 MB)


文章作者: 阿汪同学
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 阿汪同学 !
评论
  目录