[LeetCode] 1768. Merge Strings Alternately

2025. 2. 26. 12:44·코딩테스트/Python
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으로 넣는것이 아니라, 두 단어에서 각각의 글자를 가져오는 방법을 떠올려야 보다 효율적으로 풀이할 수 있다.
저작자표시 (새창열림)

'코딩테스트 > Python' 카테고리의 다른 글

[LeetCode] 345. Reverse Vowels of a String  (0) 2025.03.19
[LeetCode] 605. Can Place Flowers  (0) 2025.03.18
[Programmers] Level 2. 빛의 경로 사이클  (0) 2025.02.25
[Baekjoon] 1655. 가운데를 말해요  (0) 2025.02.25
[Programmers] Level 2. 당구 연습  (0) 2025.02.19
'코딩테스트/Python' 카테고리의 다른 글
  • [LeetCode] 345. Reverse Vowels of a String
  • [LeetCode] 605. Can Place Flowers
  • [Programmers] Level 2. 빛의 경로 사이클
  • [Baekjoon] 1655. 가운데를 말해요
swwho
swwho
일상을 데이터화하다
  • swwho
    하루한장
    swwho
  • 전체
    오늘
    어제
    • 분류 전체보기 (188)
      • ML_DL (39)
        • MUJAKJUNG (무작정 시리즈) (18)
        • 딥러닝 공부하기 (21)
      • 데이터사이언스 (1)
        • EDA (1)
        • 데이터과학을 위한 통계 (0)
      • 데이터엔지니어링 (2)
      • 논문리뷰 (2)
        • Computer Vision (2)
      • Python 활용하기 (12)
      • 코딩테스트 (127)
        • Python (109)
        • MySQL (14)
      • Git (3)
      • MySQL 활용하기 (0)
      • 일상 이야기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
swwho
[LeetCode] 1768. Merge Strings Alternately
상단으로

티스토리툴바