1768. Alternately merge strings

1768. Alternately merge strings

Title description:
Give you two strings word1 and word2. Please start with word1 and combine the strings by alternately adding letters. If one string is longer than another string, the extra letters are appended to the end of the combined string.

Returns the combined string.

Example 1:

Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The string merging situation is as follows:
word1: abc
word2: pqr
merged: apbqcr
example 2:

Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Note that word2 is longer than word1, and "rs" needs to be appended to the end of the combined string.
word1: ab
word2: pqrs
merged: apbqrs
example 3:

Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Note that word1 is longer than word2, and "cd" needs to be appended to the end of the combined string.
word1: abcd
word2: pq
merged: apbqcd

Tips:
1 <= word1.length, word2.length <= 100
word1 and word2 are composed of lowercase English letters

Link: https://leetcode-cn.com/problems/merge-strings-alternately

Problem-solving ideas:
1. Find the shortest length of the two strings;
2. Traverse the two strings according to this length, and add them sequentially;
3. Judge the two strings, if the traversal is not completed, replace The remainder is added to the result string

code show as below:

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        n = min(len(word1),len(word2))
        result = ''
        for i in range(n):
            result += word1[i] + word2[i]
        if len(word1) > n:
            result += word1[n:]
        if len(word2) > n:
            result += word2[n:]
        return result
s = Solution()
print(s.mergeAlternately('ab','pgrs'))

Guess you like

Origin blog.csdn.net/annlin2009/article/details/113998172