Interleave Two Strings
Problem
Given two strings a and b, build a new string by alternately taking the next character from a and from b, beginning with a. When one of the strings runs out, append the remaining characters of the other.
Input
a = "moon", b = "sky"Output
"mskoyon"Pairs: (m, s), (o, k), (o, y); the trailing "n" of "moon" is appended.
def interleave(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 interleave(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 interleave(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 interleave(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;
}