[LeetCode 75] Merge Strings Alternately

HL·2023년 9월 4일

LeetCode 75

목록 보기
1/3

Q:

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.

Constraints:

  • 1 <= word1.length, word2.length <= 100

A:

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        common_len = min(len(word1), len(word2))
        word1_is_shorter = True if len(word1) < len(word2) else False

        result = ''
        # common part
        for i in range(common_len):
            result += word1[i]
            result += word2[i]
        
        # now append longer word's remainder
        if word1_is_shorter: # word2 is longer
            result += word2[common_len:]
        else: # word1 is longer
            result += word1[common_len:]
        # if two were same in length,
        # word1_is_shorter is False
        # and slicing raises no error even if index is out of range,
        # so it is ok.

        return result

Result:

Solved✅

More:

  • 갖다 붙이는 게 아니라 대체하는 식으로 하면 더 빠를지도
    • 리스트만 그러려나? 문자열인 경우?
  • common_len, word1_is_shorter 없어도 됨
    class Solution(object):
      def mergeAlternately(self, word1, word2):
          """
          :type word1: str
          :type word2: str
          :rtype: str
          """
          result = []
          i = 0
          while i < len(word1) or i < len(word2):
              if i < len(word1):
                  result.append(word1[i])
              if i < len(word2):
                  result.append(word2[i])
              i += 1
          return ''.join(result)

0개의 댓글