개발이 취미인 주니어 기획자

[투포인터][JavaScript][LeetCode] #344. Reverse String 본문

문제 풀이/알고리즘 문제 풀이

[투포인터][JavaScript][LeetCode] #344. Reverse String

큐 2023. 4. 1. 11:00
728x90
반응형

#투포인터  #EASY

 

Reverse String - LeetCode

Can you solve this real interview question? 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 [https://en.wikipedia.org/wiki/In-place_algo

leetcode.com

🌷 문제 설명

✏️ LeetCode 연습문제: 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.

🎃 제한 사항
1 <= s.length <= 10^5
s[i] is a printable ascii character.

입출력 예

s result
["h","e","l","l","o"] ["o", "l", "l", "e", "h"]
["H","a","n","n","a","h"] ["h","a","n","n","a","H"]

 

🌷 내 코드

1. 투포인터

var reverseString = function(s) {
    let left = 0; // 첫 요소
    let right = s.length-1; // 마지막 요소

    while (left < right) { 
        let temp = s[left]
        s[left] = s[right]
        s[right] = temp // switch!
        left++ // 다음으로 넘어가기
        right--
    }
};

2. reverse()

ㅎㅎ 이렇게만 풀고 끝내고 싶다. (유혹 이기지 못하고 이렇게 먼저 품)

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

 

🌷 코멘트

첨에 while 조건을 (left < Math.floor(s.length/2))로 주고는 투포인터를 썼는데 reverse()보다 느려서 아니 이럴거면 왜 이걸 쓰는걸까 진지하게 고민했던 내가 유머
하지만 나는 (특히 알고리즘에 관해서 만큼은) 나를 믿지 않기에... 다시 보고 고쳤더니 예상하던 런타임 달성 🎉

 


블로그 내용에 문제가 있다면 댓글 혹은 아래로 연락주세요!

~대가리 꽃밭인 디지털 노마드가 꿈이예요~

🧚‍♀️ Gyumin Lee

📧 gyumin.q.lee@gmail.com

 

qminlee723 - Overview

noob. qminlee723 has 8 repositories available. Follow their code on GitHub.

github.com

728x90
반응형