LeetCode 1768. 交替合并字符串

LeetCode 1768. 交替合并字符串缩略图

给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。

返回 合并后的字符串 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-strings-alternately
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

LeetCode 1768. 交替合并字符串插图
OpenCV步步精深-可心科创工作室

思路:先判断谁长,然后从word1开始拼,最后把长的拼后面

python3实现

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        # 先判断谁更长
        # 从word1开始合并
        # 长的剩余的就放到末尾

        result = ""

        len_word1 = len(word1)
        len_word2 = len(word2)

        # word1长,就把word1剩余的放末尾
        if len_word1 > len_word2:
            rest_word = word1[-(len_word1 - len_word2):]
            standard = len_word2
        # 否则放word2剩余的
        elif len_word2 > len_word1:
            rest_word = word2[-(len_word2 - len_word1):]
            standard = len_word1
        else:
            rest_word = ""
            standard = len_word1

        p = 0
        while p <= standard - 1:
            result += word1[p]
            result += word2[p]
            p += 1
        result += rest_word

        return result
LeetCode 1768. 交替合并字符串插图1
OpenCV步步精深-可心科创工作室

更多干货见 OpenCV步步精深