1708. Merge Strings Alternately

Numeric_combo·2024년 9월 19일

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.

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        # create an empty list to store merged characters
        merged = []

        for i, j in zip(word1, word2): # loop to iterate each characters in word1 and word2 
            merged.append(i + j) # append each pair of the characters

        merged.append(word1[len(word2):]) # in case word1 is longer than word2
        merged.append(word2[len(word1):]) # and vice versa

        return "".join(merged) # join each elment in the merged list

Time complexity: O(n + m)
Space complexity: O(n + m)

  1. 먼저 merge되는 문자들을 저장하는 리스트를 만든다.
  2. zip 함수를 이용해서 string으로 구성된 word1, word2의 각 문자들을 짝으로 (ex. "a p", "b q") 불러와 최대한 itration 시킨다. 남는 건 버림. (word1이 word2보다 길어서 word1에 a와 b를 부르고 c, d가 남았다면 안 쓰고 내비둠)
    2-1. 불러온 짝은 merged에다가 +(=서로 concatenate) 시켜서 "ap", "bq" 꼴로 추가시켜준다.
  3. word1이 word2보다 길 경우, slicing을 이용한다. 예컨대 word1이 abcd고 word2가 pq라면 word1[len(word2):]은 word1[2:]이고, 이는 cd에 접근하는 것이며 따라서 이 cd를 merged에다가 추가 시킨다. 따라서 merged는 ["ap", "bq", "cd"]가 될 것이다.
    3-1. 만약 word1가 word2와 길이가 짧거나 같으면 empty string을 append 할 거다.
  4. 요건 반대로 word2가 word1보다 길이가 긴 경우다.
  5. 3혹은 4를 처리한 후, prefix를 ""로 하면서 merged 리스트 안에 있는 각 원소들을 join 시켜 리턴한다. 3번 과정을 예를 든다면 결국 apbqcd가 될 것이다.
profile
덕질기록용

0개의 댓글