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.
复制代码

原题链接:leetcode.com/problems/me…

您的支持是我最大的动力

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享