Merge Strings Alternately
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.
a = "moon", b = "sky""mskoyon"def merge_alternately(a, b):
i = j = 0
out = []
while i < len(a) or j < len(b):
if i < len(a):
out.append(a[i]); i += 1
if j < len(b):
out.append(b[j]); j += 1
return "".join(out)
function mergeAlternately(a, b) {
let i = 0, j = 0;
let out = "";
while (i < a.length || j < b.length) {
if (i < a.length) out += a[i++];
if (j < b.length) out += b[j++];
}
return out;
}
class Solution {
public String mergeAlternately(String a, String b) {
int i = 0, j = 0;
StringBuilder out = new StringBuilder();
while (i < a.length() || j < b.length()) {
if (i < a.length()) out.append(a.charAt(i++));
if (j < b.length()) out.append(b.charAt(j++));
}
return out.toString();
}
}
string mergeAlternately(string a, string b) {
int i = 0, j = 0;
string out = "";
while (i < (int)a.size() || j < (int)b.size()) {
if (i < (int)a.size()) out += a[i++];
if (j < (int)b.size()) out += b[j++];
}
return out;
}
Explanation
We weave two strings together, taking one letter from each in turn. The cleanest way is two index cursors that walk forward independently, so a longer string can keep going after the shorter one runs out.
We keep i for string a and j for string b. The loop runs while either string still has characters left.
On each pass, if a still has a character we append a[i] and advance i; then if b still has one we append b[j] and advance j. Because each append is guarded by its own length check, the leftover tail of whichever string is longer simply gets added at the end automatically.
Example: a = "moon", b = "sky". We pair (m,s), (o,k), (o,y), and then only a has a character left, so the final n is appended, giving "mskoyon".