题目
给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
返回 合并后的字符串 。
错误1
class Solution:def mergeAlternately(self, word1: str, word2: str) -> str:n = len(word1)m = len(word2)word3 = []i=0while i<len(word1) and i<len(word2):word3.append(word1[i])word3.append(word2[i])i +=1if i<len(word1):word3.append(word1[i:])if i<len(word2):word3.append(word2[i:])return word3
输出不是一个字符串
方法一
使用 join 连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
#!/usr/bin/python
# -*- coding: UTF-8 -*-symbol = "-";
seq = ("a", "b", "c"); # 字符串序列
print symbol.join( seq );
class Solution:def mergeAlternately(self, word1: str, word2: str) -> str:n = len(word1)m = len(word2)word3 = []i=0while i<len(word1) and i<len(word2):word3.append(word1[i])word3.append(word2[i])i +=1if i<len(word1):word3.append(word1[i:])if i<len(word2):word3.append(word2[i:])return ''.join(word3)
方法二
class Solution:def mergeAlternately(self, word1: str, word2: str) -> str:ans = []for x, y in zip_longest(word1, word2):if x: ans.append(x)if y: ans.append(y)return ''.join(ans)```