Given two strings <span>word1</span> and <span>word2</span>. You need to merge the strings by adding letters alternately starting from <span>word1</span>. If one string is longer than the other, append the extra letters to the end of the merged string. Return the merged string.
Example 1: Input: word1 = “abc”, word2 = “pqr” Output: “apbqcr” Explanation: The merging of the strings is as follows: word1: a b c word2: p q r Merged: a p b q c r
Example 2: Input: word1 = “ab”, word2 = “pqrs” Output: “apbqrs” Explanation: Note that word2 is longer than word1, so “rs” needs to be appended to the end of the merged string. word1: a b word2: p q r s Merged: a p b q r s
Example 3: Input: word1 = “abcd”, word2 = “pq” Output: “apbqcd” Explanation: Note that word1 is longer than word2, so “cd” needs to be appended to the end of the merged string. word1: a b c d word2: p q Merged: a p b q c d
In this problem, we will use the append() syntax, which is a built-in method of the list object used to add elements to the end of a list.
[!note] Basic syntax of append()
list.append(element)list: The target list to which you want to add elementselement: The element to be added to the end of the list (can be of any data type)
Features:
(1) In-place modification: append() directly modifies the original list instead of returning a new list (2) One at a time: only one element can be added at a time (3) Added to the end: new elements always become the last element of the list (4) No return value: this method returns None instead of the modified list
Solution:
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
merged = []
i = 0
j = 0
while i < len(word1) and j < len(word2):
merged.append(word1[i])
merged.append(word2[j])
i += 1
j += 1
merged.append(word1[i:])
merged.append(word2[j:])
return ''.join(merged)
solution = Solution()
print(solution.mergeAlternately("abc","pqr"))
We simply utilized the append() method to sequentially input letters from the strings into the list, achieving the alternate merging of the two strings.