코딩테스트/Python

[LeetCode] 1768. Merge Strings Alternately

swwho 2025. 2. 26. 12:44
728x90
반응형

🔗 Problem Link

https://leetcode.com/problems/merge-strings-alternately/description/


❔Thinking

  • word1, word2 두 단어가 주어질 때, 두 단어의 각 글자를 번갈아 합친 단어를 반환한다.
  • 길이가 다르다면, 남은 길이의 단어는 그대로 붙인다.
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1:  a   b   c
word2:    p   q   r
merged: a p b q c r

💻Solution

1. stack을 활용한 풀이

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        output = []
        word1 = list(word1)[::-1]
        word2 = list(word2)[::-1]
        while word1 or word2:
            if word1:
                output.append(word1.pop())
            if word2:
                output.append(word2.pop())
        return ''.join(output)

 

2. index를 활용한 풀이

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        n = max(len(word1), len(word2))
        output = []
        for i in range(n):
            if i < len(word1):
                output.append(word1[i])
            if i < len(word2):
                output.append(word2[i])
        return ''.join(output)

🗝️keypoint

  1. 한번에 하나의 글자만을 output으로 넣는것이 아니라, 두 단어에서 각각의 글자를 가져오는 방법을 떠올려야 보다 효율적으로 풀이할 수 있다.