leetcode 1768. Merge Strings Alternately(python)

描述

You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

Return the merged string.

Example 1:

Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1:  a   b   c
word2:    p   q   r
merged: a p b q c r

Example 2:

Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1:  a   b 
word2:    p   q   r   s
merged: a p b q   r   s

Example 3:

Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1:  a   b   c   d
word2:    p   q 
merged: a p b q c   d

Note:

1 <= word1.length, word2.length <= 100
word1 and word2 consist of lowercase English letters.

解析

根据题意,只需要将 word1 和 word2 中每个字符,交替追加到新的字符串 res 末尾,然后将长度较长的那个字符串多出来的字符串直接追加到 res 末尾即可得到结果。

解答

 class Solution(object):
    def mergeAlternately(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: str
        """
        res = ''
        min_length = min(len(word2), len(word1))
        for i in range(min_length):
            res = res + word1[i] + word2[i]
        res += word1[min_length:] + word2[min_length:]
        return res           	      

运行结果

Runtime: 24 ms, faster than 100.00% of Python online submissions for Merge Strings Alternately.
Memory Usage: 13.6 MB, less than 100.00% of Python online submissions for Merge Strings Alternately.

原题链接:https://leetcode.com/problems/merge-strings-alternately/

您的支持是我最大的动力

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王大丫丫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值