[LeetCode / Easy] 1768. Merge Strings Alternately (Java)

이하얀·2025년 1월 21일
0

📙 LeetCode

목록 보기
3/13

💬 Info



Problem

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 letters onto the end of the merged string.

Return the merged string.



Example

예시 1

  • 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

예시 2

  • Input: word1 = "ab", word2 = "pqrs"
  • Output: "apbqrs"
  • Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1:  a   b 
word2:    p   q   r   s
merged: a p b q   r   s

예시 3

  • Input: word1 = "abcd", word2 = "pq"
  • Output: "apbqcd"
  • Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1:  a   b   c   d
word2:    p   q 
merged: a p b q c   d


Constraints

  • 1 <= word1.length, word2.length <= 100
  • word1 and word2 consist of lowercase English letters.


문제 이해

  • 주어진 두 word를 병합
    • 하나의 문자가 다른 하나의 문자보다 길다 -> 합친 문장 뒤에 붙이는 방식


알고리즘

풀이 시간 : 12분

  • 두 단어의 길이를 구하기 + 결과 저장할 배열 생성
  • 두 단어의 문자를 차례로 결과 배열에 추가
  • 두 단어 중 더 긴 단어의 남은 문자 추가
  • 배열을 문자열로 변환 및 반환
class Solution {
    public String mergeAlternately(String word1, String word2) {
        int len1 = word1.length();
        int len2 = word2.length();
        
        char[] result = new char[len1 + len2];
        
        int index = 0;
        int i = 0;

        while (i < len1 || i < len2) {
            if (i < len1) result[index++] = word1.charAt(i);
            if (i < len2) result[index++] = word2.charAt(i);
            i++;
        }
        return new String(result);
    }
}


결과

profile
언젠가 내 코드로 세상에 기여할 수 있도록, Data Science&BE 개발 기록 노트☘️

0개의 댓글