题目:
给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
返回 合并后的字符串 。
示例 1:
输入:word1 = "abc", word2 = "pqr"
输出:"apbqcr"
解释:字符串合并情况如下所示:
word1: a b c
word2: p q r
合并后: a p b q c r
提示:
1 <= word1.length, word2.length <= 100
word1 和 word2 由小写英文字母组成
解题思路:
每次分别从 word1
和 word2
获取一个字符。当一个字符串用完了之后,while 循环停止,然后把另外一个字符串的剩余部分,也补充到结果中
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
str = ""
c1, c2 =0, 0
while c1 < len(word1) and c2 < len(word2):
str += word1[c1] + word2[c2]
c1 +=1
c2 +=1
if c1 != len(word1):
str += word1[c1:]
if c2 != len(word2):
str += word2[c2:]
return str
执行结果:
通过
执行用时:32 ms, 在所有 Python3 提交中击败了91.76%的用户
内存消耗:15 MB, 在所有 Python3 提交中击败了21.51%的用户