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.
- def l:int is the min length of the two words.
- def merge(word1, word2) to process the two words.
- def ans:list to store the return result.
- loop len(word1) in i
- ans.append(word1[i]) and ans.append(word2[i])
- return ans
- judge len(word1) < len(word2): ans.append(word2[l:])
- judge len(word1) > len(word2): ans.append(word1[l:])
- 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
- def m:int is the length of the word1
- def n:int is the length of the word2
- def i,j:int is two pointer
- def ans:list to store the final result
- while i < m or j < n
- if i < m: ans += word1[i], i+=1
- if j < n: ans += word2[i], j+=1
- 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)