LeetCode 1768
1768. 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.
Return the merged string.
Solution
We can solve this in a recursive way. When we are grabbing one character from each string how do we know we are finished? When the string is empty So in this case we must return the other string to be appended on.
if word1 == "":
return word2
if word2 == "":
return word1
Now, that we have our base cases we must look at the recursive call.
We must grab one character from word1
then word2
, and finally call the function again on the rest of the two words, after the first character.
return word1[0] + word2[0] + self.mergeAlternately(word1[1:], word2[1:])