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.
word1과 word2 두 개의 문자열이 주어집니다. word1부터 시작하여 word1과 word2의 문자열을 교대로 문자를 한개씩 추가하여 문자열을 병합합니다. 문자열이 다른 문자열보다 길면 병합된 문자열의 끝에 추가 문자를 추가합니다.
Return : 병합된 문자열을 반환합니다.
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
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
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
1 <= word1.length, word2.length <= 100
word1 and word2 consist of lowercase English letters.
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();
}
}