💬 Info
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: a b c
word2: p q r
merged: a p b q c r
word1: a b
word2: p q r s
merged: a p b q r s
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.풀이 시간 : 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);
}
}