알고리즘 & 자료구조/문제 풀이

[LeetCode][Java] 1768. Merge Strings Alternately

수수다 2026. 4. 16. 02:45

https://leetcode.com/problems/merge-strings-alternately/description/?envType=study-plan-v2&envId=leetcode-75

 

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 : 교차로