给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
返回 合并后的字符串 。
示例 1:
输入:word1 = "abc", word2 = "pqr"
输出:"apbqcr"
解释:字符串合并情况如下所示:
word1: a b c
word2: p q r
合并后: a p b q c r
示例 2:
输入:word1 = "ab", word2 = "pqrs"
输出:"apbqrs"
解释:注意,word2 比 word1 长,"rs" 需要追加到合并后字符串的末尾。
word1: a b
word2: p q r s
合并后: a p b q r s
示例 3:
输入:word1 = "abcd", word2 = "pq"
输出:"apbqcd"
解释:注意,word1 比 word2 长,"cd" 需要追加到合并后字符串的末尾。
word1: a b c d
word2: p q
合并后: a p b q c d
思路:简单模拟题,用while控制循环,循环条件是len(word1) or len(word2)
1 class Solution: 2 def mergeAlternately(self, word1: str, word2: str) -> str: 3 m, n, i, j = len(word1), len(word2), 0, 0 4 res = '' 5 while i < m or j < n: 6 if i < m: 7 res += word1[i] 8 i += 1 9 if j < n: 10 res += word2[j] 11 j += 1 12 return res
标签:res,合并,len,交替,1768,word1,word2,字符串 From: https://www.cnblogs.com/wangpengcufe/p/16818229.html