본문 바로가기
프론트엔드로 가는 길/Leet코드 75

1. 문자열의 단어 반전

by woody-j 2023. 9. 18.

프로그래머스 문제를 100문제를 풀었다!

그래서 Leet 코드 75를 풀고자한다

 

https://leetcode.com/problems/reverse-words-in-a-string/description/?source=submission-ac 

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
 

 
Constraints:
  • 1 <= s.length <= 104
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.

 

[첫번째 풀이]

 

var reverseWords = function(s) {
   let result=[];
// 1. 문자를 " " 기준으로 나눈다.
// 2. " " 나눈 배열에 포함 되어있는 " "를 모두 없앤다.
// 3. 문자만 남은 배열로 역순으로 나열한다.
const nonSpaceArr = s.split(' ').filter((item)=> item!=="").reverse();
// 4. 단어와 단어 사이에 " "을 포함시켜준다.
for(let i=0; i<nonSpaceArr.length; i++){
    if(i === nonSpaceArr.length - 1){
        result.push(nonSpaceArr[i]);
        return result.join('')
    }
result.push(nonSpaceArr[i] + " ");
}
return result.join('')
};

스스로도 다소 길고 복잡하다고 생각한다.

단어 사이에 " "을 포함시키는 다른 무언가가 있을 것 같은데..

다시 생각해보자

 

[두번째 풀이]

var reverseWords = function(s) {
// 1. 문자를 " " 기준으로 나눈다.
// 2. " " 나눈 배열에 포함 되어있는 " "를 모두 없앤다.
// 3. 문자만 남은 배열로 역순으로 나열한다.
// 4. 단어와 단어 사이에 " "을 포함시켜준다.
return s.split(' ').filter((item)=> item!=="").reverse().join(' ')
};

단어 사이에 " "을 포함시키는 다른 무언가가 있을 것 같은데.. -> 굳이 단어 사이에 " "을 넣으려고 하지않아도 됐다.

나는 join(" ")을 하면 끝 원소도 같이 " "가 포함 되는 줄 알았다.

join(" ")이 알아서 맨 끝 원소를 제외하고 " "포함해서 병합해줬다.


Intuition

이 코드의 목적은 문자열에서 단어의 순서를 뒤집는 것입니다.
이를 위해 주어진 문자열을 공백을 기준으로 분할하고,
분할된 단어들을 뒤집은 후 다시 조합합니다.

Approach

주어진 문자열을 공백을 기준으로 분할하여 배열로 변환합니다.
빈 문자열을 제거하기 위해 배열을 필터링합니다.
필터링된 배열을 뒤집습니다.
뒤집힌 배열을 다시 공백으로 연결하여 최종 결과 문자열을 생성합니다.


Complexity

Time complexity: O(n) 

주어진 문자열의 길이에 선형 시간복잡도에 비례합니다.
문자열을 분할하고, 필터링하며, 뒤집는 각 단계는 선형 시간에 작동합니다.
Space complexity: O(n) 

입력 문자열과 동일한 크기의 배열이 생성되므로,
공간 복잡도는 입력 문자열의 길이에 비례합니다.

'프론트엔드로 가는 길 > Leet코드 75' 카테고리의 다른 글

2. 문자열을 교대로 병합  (1) 2023.09.19