📚

Python勉強日記: 1/75

2025/02/20に公開

今日の問題

You are given two strings word1 and word2.(あなたはword1とword2の2つの文字列が渡される) Merge the strings by adding letters in alternating order(交互に文字を文字列に統合せよ:lettersは文字:in alternating orderは交互に), starting with word1(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
 

Constraints:

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

解答

class Solution(object):
    def mergeAlternately(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: str
        """
        merged = []
        # 最終的に返す文字列
        i, j = 0, 0
        
        while i < len(word1) and j < len(word2):
            merged.append(word1[i])
            merged.append(word2[j])
            i += 1
            j += 1
        # 同じ長さまで交互に文字を追加していく
        
        # Append remaining characters from word1 or word2
        if i < len(word1):
            merged.append(word1[i:])
            # i番目以降を追加(i:)
        if j < len(word2):
            merged.append(word2[j:])
        
        return "".join(merged)
        # "-"にしたら、文字の間に-が追加される

こんな感じ

メモリをもっと使わないようにするために

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        def generator():
            i, j = 0, 0
            while i < len(word1) and j < len(word2):
                yield word1[i]
                yield word2[j]
                i += 1
                j += 1
            
            yield from word1[i:]  # 残りの部分を追加
            yield from word2[j:]  # 残りの部分を追加

        return "".join(generator())

# Example usage
solution = Solution()
word1 = "abc"
word2 = "pqr"
print(solution.mergeAlternately(word1, word2))

yieldを使ったら簡単に追加できるみたい

Discussion