Skip to main content

Command Palette

Search for a command to run...

[Leetcode75] 1. Merge Strings Alternately

Published
•1 min read•View as Markdown

[1] 문제

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.

두개의 string 값을 받은 뒤 하나하나씩 섞어서 merged string을 리턴해줘야 한다!

<example>

Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"

[2] 풀이

function mergeAlternately(word1: string, word2: string): string {
    const longWord = word1.length >= word2.length? word1 : word2;
    const shortWordLength = word1.length >= word2.length? word2.length : word1.length;

    let result = '';
    for(let i = 0; i < shortWordLength; i++) {
        result += word1[i]
        result += word2[i]
    }
    result += longWord.substring(shortWordLength)

    return result
};
  1. 여기서는 word1과 word2중 뭐가 더 긴지를 몰라서 먼저 긴 문자열과 짧은 문자열의 길이를 따로 변수에 저장했다

  2. 짧은 문자열 길이만큼은 word1과 word2가 왔다갔다하면서 쓰여야 해서 그 길이만큼은 for문을 돌리며 word1의 글자와 word2의 글자를 하나씩 추가해준다 (항상 word1이 먼저여야한다)

더이상 중복되는 길이가 없으면 긴 문자열에서 남은 길이만큼 (substring을 이용) 바로 결과값에 더해준다.

✏️
Leetcode75 문제세트를 하루에 하나씩 푸는 것을 목표로 다시 기본적인 알고리즘과 자료구조 공부를 시작해봐야겠다 ㅜㅜ 오랜만에 하려니까 머리가 안돌아가요ㅜㅠㅠㅠ

More from this blog

[Leetcode] LeetHub이용해서 자동으로 GitHub 커밋하기

[1] GitHub에 릿코드용 레파지토리 생성하기 leetcode라는 이름으로 레파지토리를 하나 먼저 생성해준다. [2] 크롬 익스텐션 LeetHub 설치하기 [링크](https://chrome.google.com/webstore/detail/leethub/aciombdipochlnkbpcbgdpjffcfdbggi?hl=en) 로 가서 익스텐션을 설치해준다! 설치 후 핀으로 고정을 하면 저렇게 상단바에 뜨고 누르면 깃헙 계정으로 인증을 하...

Nov 11, 20231 min read

[JS/TS] Object.keys()의 'default'는 무엇인가

JavaScript 또는 TypeScript에서 Object.keys()를 사용하여 모듈에서 가져온 객체의 키를 배열로 변환하면, 때때로 예상치 못한 'default' 키를 보게 된다. 이것은 ES6 모듈 시스템과 관련이 있다. ES6 모듈에서 export default 구문을 사용하면, 기본적으로 모듈은 'default'라는 이름의 키로 해당 값을 내보낸다. import 구문을 사용하여 이 모듈을 가져올 때, 내보낸 'default' 값에 직...

Nov 8, 20232 min read

707's devlog

7 posts