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

2. 문자열을 교대로 병합

by woody-j 2023. 9. 19.

 

https://leetcode.com/problems/merge-strings-alternately/?envType=study-plan-v2&envId=leetcode-75 

 

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


You are given two strings word1 and word2.
Merge the strings by adding letters in alternating order, starting with word1.
If a string is longer than the other, append the additional letters onto the end of the merged string.

Return the merged string.
 



Constraints:
  • 1 <= word1.length, word2.length <= 100
  • word1 and word2 consist of lowercase English letters.

 

[첫번째 풀이]

function (word1, word2) {
  let newArr = [];
  const wordArr1 = word1.split("");
  const wordArr2 = word2.split("");
  let wordArrLength = 0;
  wordArr1.length > wordArr2.length
    ? (wordArrLength = wordArr1.length)
    : (wordArrLength = wordArr2.length);

  for (let i = 0; i < wordArrLength; i++) {
    newArr.push(wordArr1[i]);
    newArr.push(wordArr2[i]);
  }
  let result = newArr.filter((item) => item !== undefined).join("");
  return result;
};

악 너무 느령!

 

 const wordArr1=word1.split('');

split말고 문자열을 배열로 만드는 메서드가 또 뭐 있더라

 

spread 연산자()

 const wordArr1 = [...word1]

spread 연산자()

Array.from 메서드

 const wordArr1 = Array.from(word1)

Array.from 메서드

더 줄이자!

 

[두번째 풀이]

 

아앗..word1[2]

문자열도 특정위치 문자를 뽑을 수 있다는 것을 간과했다..! 굳이 배열로 안만들어도...

var mergeAlternately = function(word1, word2){
  let newString = "";
  let maxLength = word2.length;
  if (word1.length > word2.length) {
    maxLength = word1.length;
  }
  for (let i = 0; i < maxLength; i++) {
    if (word1.length > i) {
      newString += word1[i];
    }
    if (word2.length > i) {
      newString += word2[i];
    }
  }
  return newString;
};
    newString += word1[i];

 

이렇게 문자열도 추가가 된다는 것을 잊지말라..!


Intuition

각각의 문자를 사이에 섞어 하나의 문자로 조합합니다.


Approach

1. word1과 word2의 길이를 비교하여 새로 만들 문자의 최대 문자 길이를 정합니다.
2. 각각의 문자의 길이가 i보다 작아질 때까지 반복하며 newString에 문자를 추가해줍니다.
3. 모든 문자를 다 순회했다면, newString를 반환합니다.

 

Complexity


Time complexity: O(max(N, M))
여기서 N은 word1의 길이이고, M은 word2의 길이입니다. 반복문은 두 문자열 중 더 긴 문자열의 길이를 기준으로 돌기 때문에 최대 문자열의 길이에 비례하는 시간이 걸립니다.
Space complexity: O(max(N, M))
추가적인 메모리 공간을 사용하지 않고 문자열을 조합하므로 입력 문자열과 동일한 크기의 공간만 필요합니다.

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

1. 문자열의 단어 반전  (0) 2023.09.18