class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
lista = []
for x,y in zip_longest(word1,word2):
if x: lista.append(x)
if y: lista.append(y)
return ''.join(lista)
代码中,是使用了zip_longest函数将两个字符串word1
和word2
按照最长的长度进行合并。在每一次迭代中,zip_longest
函数会返回两个字符串中对应位置的字符,如果某个字符串长度不够,则使用fillvalue进行填充。
在for循环中,使用了两个if语句来判断当前位置的字符是否存在。如果存在,则将其添加到列表lista
中。这样做的目的是为了保证合并后的字符串中不包含填充字符。
具体来说:
-
第一个if语句
if x: lista.append(x)
用来判断字符串word1
当前位置的字符是否存在,如果存在则将其添加到lista
中。 -
第二个if语句
if y: lista.append(y)
用来判断字符串word2
当前位置的字符是否存在,如果存在则将其添加到lista
中。
最后,通过return ''.join(lista)
将列表lista
中的字符连接成一个字符串并返回。