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

[투포인터][JavaScript][LeetCode] #557. Reverse Words in a String III 본문

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

[투포인터][JavaScript][LeetCode] #557. Reverse Words in a String III

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

#투포인터  #EASY

 

Reverse Words in a String III - LeetCode

Can you solve this real interview question? Reverse Words in a String III - Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.   Example 1: Input: s = "Let's take Leet

leetcode.com

🌷 문제 설명

✏️ LeetCode 연습문제: Reverse Words in a String III
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

🎃 제한 사항
1 <= s.length <= 5 * 10^4
s contains printable ASCII characters.
s does not contain any leading or trailing spaces.
There is at least one word in s.
All the words in s are separated by a single space.

입출력 예

s result
"Let's Take LeetCode contest" "s'teL ekat edoCteeL tsetnoc"
"God Ding" "doG gniD"

 

🌷 내 코드

1. 투포인터

어어.....? 왤케느려 머가 잘못된거지? - 근데 메모리를 좀 덜 쓰긴 했다..0.5MB.. 이 정도면 많이 절약한건..가? 몰?루

var reverseWords = function(s) {
    let word = s.split(' ')

    for (let i=0; i<word.length; i++) {
        let left = 0; 
        let right = word[i].length-1;
        let al = word[i].split('')

        while (left < right) {
            let temp = al[left]
            al[left] = al[right]
            al[right] = temp
            left++
            right--
        }
        word[i] = al.join('')
    }

    return word.join(' ')
}

2. 무지성

ㅋㅋㅋㅋㅋㅋㅋㅋㅋ아니..이러면 안되는거 아닌가요?

var reverseWords = function(s) {
    arr = s.split(' ')
    answer = []
    for (let i=0; i < arr.length; i++) {
        answer.push(arr[i].split('').reverse().join(''))
    }

    return answer.join(' ')
}

 

🌷 코멘트

ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ
투포인터 쓴게 더 느려서... 뭐가 잘못된거같아서 다른 사람들 코드를 넣어봤는데 효율성 더 안좋음;;;;; 뭘까 메모리 조금 덜 쓴거 정도..? 그렇다고 엄청 드라마틱한 변화 같진 않은데.... 알려 줄 사람 어디없나 😇

 


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

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

🧚‍♀️ Gyumin Lee

📧 gyumin.q.lee@gmail.com

 

qminlee723 - Overview

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

github.com

728x90
반응형