1768. Merge Strings Alternately
Problem
Interleave word1 and word2 letter by letter, starting with word1; when one runs out, append the rest of the other.
Example: word1 = "ab", word2 = "pqrs" → "apbqrs"
Take one character from each word in turn; when one runs out, append the rest of the other.
Complexity: O(n + m).
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
return "".join(a + b for a, b in itertools.zip_longest(word1, word2, fillvalue=""))
assert Solution().mergeAlternately("abc", "pqr") == "apbqcr"
assert Solution().mergeAlternately("ab", "pqrs") == "apbqrs"
assert Solution().mergeAlternately("abcd", "pq") == "apbqcd"
class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Math.max(word1.length(), word2.length()); i++) {
if (i < word1.length()) sb.append(word1.charAt(i));
if (i < word2.length()) sb.append(word2.charAt(i));
}
return sb.toString();
}
}
func mergeAlternately(word1 string, word2 string) string {
var sb strings.Builder
for i := 0; i < len(word1) || i < len(word2); i++ {
if i < len(word1) {
sb.WriteByte(word1[i])
}
if i < len(word2) {
sb.WriteByte(word2[i])
}
}
return sb.String()
}