Merge Strings Alternately - LeetCode
Can you solve this real interview question? Merge Strings Alternately - 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 le
leetcode.com
word1부터 번갈아가면서 하나의 문자열이 끝날 때까지 append
그 이후 글자가 남은 단어의 글자를 하나씩 append
import java.util.*;
class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder sb = new StringBuilder();
int length1 = word1.length();
int length2 = word2.length();
int word1Idx = 0;
int word2Idx = 0;
while(word1Idx < length1 && word2Idx < length2) {
sb.append(word1.charAt(word1Idx++));
sb.append(word2.charAt(word2Idx++));
}
while(word1Idx < length1) {
sb.append(word1.charAt(word1Idx++));
}
while(word2Idx < length2) {
sb.append(word2.charAt(word2Idx++));
}
return sb.toString();
}
}
alternately : 번갈아
alternating : 교차로
'알고리즘 & 자료구조 > 문제 풀이' 카테고리의 다른 글
| [프로그래머스 알고리즘 고득점 Kit][이분탐색][Java] 징검다리 (0) | 2026.03.31 |
|---|---|
| [프로그래머스 알고리즘 고득점 Kit][그래프][Java] 순위 (0) | 2026.03.29 |
| [프로그래머스 알고리즘 고득점 Kit][힙(Heap)][Java] 더 맵게 (0) | 2026.03.29 |
| [프로그래머스 알고리즘 고득점 Kit][깊이/너비 우선 탐색(DFS/BFS)][Java] 네트워크 (0) | 2026.03.08 |
| [프로그래머스 알고리즘 고득점 Kit][그래프][Java] 가장 먼 노드 (0) | 2026.03.07 |