나의 발자취
[String] 1768. Merge Strings Alternately 본문
음.. 새해니까 가볍게 몸풀기로 시작
하루에 최소 하나의 문제를 재미로 풀어보는 시간을 가지겠다.
https://leetcode.com/problems/merge-strings-alternately/description/

푸는 시간은 파이썬으로 10분 걸렸고 시간 복잡도는 O(N)이라 메모리 효율도는 높은 편이다.
문제 접근 방법
단순히 이중 루프를 활용하는 것이 아니라 인덱스가 같다는 개념을 활용하면 루프 하나 안에서 문자열을 결합할 수 있다.
주의사항
다만, index out of range 에러 해결을 위해 for loop 안에 if 조건을 추가해주어야한다.
이 조건문 없이 그대로 실행하게 되면, 문자열의 길이가 같다는 전제만 되기 때문에 주어진 문제와 같이 word1과 word2가 다른 길이를 가질 때 오류 없이 작동하게 하려면 조건을 추가하자.
코드
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
output = ""
for i in range(0, len(word1+word2)):
if i < len(word1):
output += word1[i]
if i < len(word2):
output += word2[i]
return output'알고리즘' 카테고리의 다른 글
| Two Pointers 기법이란? (Why / When / How to use) (0) | 2025.02.13 |
|---|---|
| 334. Increasing Triplet Subsequence (0) | 2025.01.30 |
| [그리디] 605. Can Place Flowers (2) | 2025.01.04 |
| [Two Pointers] 345. Reverse Vowels of a String (0) | 2025.01.04 |
| [Ad-Hoc] 1431. Kids With the Greatest Number of Candies (1) | 2025.01.03 |
Comments