[JS] Reverse String

2022. 7. 29. 15:55

🔒 문제 (LeetCode 344)

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.

Constraints:

 

🌊 입출력

Example 1:

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

Example 2:

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

 


 

🔑 해결

🌌 알고리즘 - two pointers

1)

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function(s) {
    const len = s.length;
    for(let i = 0; i < len/2; i++) {
        const tmp = s[i];
        s[i] = s[len - i - 1];
        s[len - i - 1] = tmp;
    }
};

 

2)

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function(s) {
    let l = 0;
    let r = s.length - 1;
    
    while(l < r) {
        const tmp = s[l];
        s[l] = s[r];
        s[r] = tmp;
        l++;
        r--;
    }
};

'코딩테스트 (JS) > 투포인터' 카테고리의 다른 글

[JS] Middle of the Linked List  (0) 2022.07.29
[JS] Reverse Words in a String III  (0) 2022.07.29
[JS] Two Sum II - Input Array Is Sorted  (0) 2022.07.29
[JS] Move Zeroes  (0) 2022.07.29
[JS] Rotate Array  (0) 2022.07.29

+ Recent posts