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.
Constraints:
- 1 <= word1.length, word2.length <= 100
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
common_len = min(len(word1), len(word2))
word1_is_shorter = True if len(word1) < len(word2) else False
result = ''
# common part
for i in range(common_len):
result += word1[i]
result += word2[i]
# now append longer word's remainder
if word1_is_shorter: # word2 is longer
result += word2[common_len:]
else: # word1 is longer
result += word1[common_len:]
# if two were same in length,
# word1_is_shorter is False
# and slicing raises no error even if index is out of range,
# so it is ok.
return result
➡ Solved✅
common_len, word1_is_shorter 없어도 됨class Solution(object):
def mergeAlternately(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: str
"""
result = []
i = 0
while i < len(word1) or i < len(word2):
if i < len(word1):
result.append(word1[i])
if i < len(word2):
result.append(word2[i])
i += 1
return ''.join(result)