1768. Merge Strings Alternately

 

Promble

link: https://leetcode.com/problems/merge-strings-alternately/

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.

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
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
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

Approach 1

Thought

use python str slice method.

  1. def l:int is the min length of the two words.
  2. def merge(word1, word2) to process the two words.
    1. def ans:list to store the return result.
    2. loop len(word1) in i
    3. ans.append(word1[i]) and ans.append(word2[i])
    4. return ans
  3. judge len(word1) < len(word2): ans.append(word2[l:])
  4. judge len(word1) > len(word2): ans.append(word1[l:])
  5. return ‘‘.join(ans) # ans is List, need to convert ot str.

Code

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:

        l = min(len(word1), len(word2))
        ans = self.merge(word1[:l], word2[:l])

        if len(word1) < len(word2):
            ans.append(word2[l:])
        else:
            ans.append(word1[l:])

        return ''.join(ans) 

    def merge(self, word1, word2):
        ans = []
        for i in range(len(word1)):
            ans.append(word1[i])
            ans.append(word2[i])

        return ans

Approach 2

two pointers method

Thought

  1. def m:int is the length of the word1
  2. def n:int is the length of the word2
  3. def i,j:int is two pointer
  4. def ans:list to store the final result
  5. while i < m or j < n
    1. if i < m: ans += word1[i], i+=1
    2. if j < n: ans += word2[i], j+=1
  6. return ‘‘.join(ans) # the ans is list, need to convert to str

Code

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        m = len(word1)
        n = len(word2)
        i = 0
        j = 0 
        ans = []

        while i < m or j < n:
            if i < m:
                ans += word1[i]
                i += 1
            if j < n:
                ans += word2[j]
                j += 1

        return ''.join(ans)