wgrgwg-dev
[LeetCode] 1768. Merge Strings Alternately [Java] 본문
1768. Merge Strings Alternately
https://leetcode.com/problems/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 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
Example 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
Example 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 <= 100word1andword2consist of lowercase English letters.
문자열 두 개의 문자들을 번갈아 옮겨 합쳐 하나의 문자열로 만드는 문제였다. 각 단어를 동시에 순회하는데, 단어별로 사용하는 인덱스는 i, j로 나누어 사용하였다. i, j 둘중 하나가 문자끝에 도달하면 반복을 종료하고, 아직 문자끝에 도달하지 못한 인덱스값을 이용해서 해당 단어이 나머지 문자들을 substring 메서드를 통해서 옮겨준다.
class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder sb = new StringBuilder();
int i = 0, j = 0;
while(i<word1.length() && j<word2.length()){
sb.append(word1.charAt(i));
sb.append(word2.charAt(j));
i++;
j++;
}
if(i!=word1.length()){
sb.append(word1.substring(i));
}
if(j!=word2.length()){
sb.append(word2.substring(j));
}
return sb.toString();
}
}'알고리즘 > LeetCode' 카테고리의 다른 글
| [LeetCode] 841. Keys and Rooms [Java] (0) | 2026.01.20 |
|---|---|
| [LeetCode] 2095. Delete the Middle Node of a Linked List [Java] (0) | 2026.01.18 |
| [LeetCode] 2390. Removing Stars From a String [Java] (0) | 2026.01.17 |