[algorithm][leetcode] 344. Reverse String

임택·2020년 2월 10일
0

알고리즘

목록 보기
5/63

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

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

// var reverseString = function(s) {
//     s.reverse();
//     return s;
// };

var reverseString = function(s) {
    const len = s.length;
    for (let i = 0; i < len / 2; i++) {
        const temp = s[i];
        s[i] = s[len - i - 1];
        s[len - i - 1] = temp;
    }
    return s;
};
profile
캬-!

0개의 댓글