티스토리 뷰

알고리즘

Leetcode 344. Reverse String

진고월드 2023. 3. 10. 23:48

알고리즘 문제를 올리는건 처음이다. 앞으로 자주 올릴 예정인데, 프로젝트로 글 쓸 시간이 부족해서는 아니다. 뭔가 날로 먹는 느낌이지만 한 번 풀어볼까.


◆ 문제

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.

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"]

Constraints:

 


 

◆ 나의 답안:

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function(s) {
    return s.reverse()
};

...겨우 리버스 하나 맞췄다고 블로깅 하면 욕 먹겠지? 까먹지 않고, 새로운 풀이법을 기록하기 위해 다른 풀이 방법을 써봤다.

 

◆ 다른 답안:

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

배열을 바꾸는 방법이 핵심이다. 자주 안쓰니 떠올리지 못하는 방법이다. 이 외에도 reverse를 안쓰는 방법에 대해 고민해봐야겠다.

'알고리즘' 카테고리의 다른 글

Leetcode 94. Binary Tree Inorder Traversal  (5) 2023.04.06
Leetcode 746. Min Cost Climbing Stairs  (6) 2023.03.31
Leetcode 139. Word Break  (6) 2023.03.30
Leetcode 70. Climbing Stairs  (6) 2023.03.27
Leetcode 190. Valid Palindrome II  (5) 2023.03.23
댓글