📌 문제 링크 :
https://leetcode.com/problems/merge-strings-alternately
✅ 내 풀이(Success) :
class Solution {
public String mergeAlternately(String word1, String word2) {
int l1 = word1.length(), l2 = word2.length();
int idx1 = 0, idx2 = 0;
StringBuilder sb = new StringBuilder();
while (true) {
if (idx1 == l1 || idx2 == l2) {
break;
}
sb.append(word1.charAt(idx1++));
sb.append(word2.charAt(idx2++));
}
while (idx1 < l1) {
sb.append(word1.charAt(idx1++));
}
while (idx2 < l2) {
sb.append(word2.charAt(idx2++));
}
return sb.toString();
}
}

🧐 리뷰 :
어제 자기 전에 문제를 읽자마자 떠올린 풀이를 제출했더니 한 번에 풀렸다. 그만큼 쉬운 문제인 것 같다.
문제를 풀고 Solutions에 공개되어 있는 풀이 중에서 가장 많은 좋아요를 받은 코드를 아래에 첨부했다.
나는 두 개의 문자열을 순회하니까 각각 다른 인덱스 변수를 선언했는데, 인덱스 변수를 하나만 사용한 점과
반복문 안의 2개의 조건문으로 문제를 해결한 점이 인상깊었다.
🏷️ 참고 자료:
class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder result = new StringBuilder();
int i = 0;
while (i < word1.length() || i < word2.length()) {
if (i < word1.length()) {
result.append(word1.charAt(i));
}
if (i < word2.length()) {
result.append(word2.charAt(i));
}
i++;
}
return result.toString();
}
}
'알고리즘 문제 풀이: 자바 > LeetCode' 카테고리의 다른 글
| 1732. Find the Highest Altitude (0) | 2025.11.01 |
|---|---|
| 2215. Find the Difference of Two Arrays (0) | 2025.10.31 |
| 643. Maximum Average Subarray I (0) | 2025.10.30 |
| 1071. Greatest Common Divisor of Strings (0) | 2025.10.29 |
| 392. Is Subsequence (0) | 2025.10.27 |
댓글