1768. Merge Strings Alternately
Two Pointers, String, AMateList ·Problem Statement
link: LeetCode.cn LeetCode 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.
Example:
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Constraints: 1 <= word1.length, word2.length <= 100 word1 and word2 consist of lowercase English letters.
Solution Approach
Merge characters from both strings alternately and append any remaining characters from the longer string to the result.
Algorithm
- Iterate through both strings simultaneously: Use a loop to alternate appending characters from word1 and word2 to the result string until reaching the end of the shorter string.
- Handle remaining characters: After the loop, concatenate the remaining characters from the longer string to the result string.
- Return the merged string: Construct and return the final merged string by combining the alternated characters and any leftover characters.
Complexity
time complexity: O(n) space complexity: O(n)
Implement
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
l1, l2 = len(word1), len(word2)
i = 0
res = ""
while i < l1 and i < l2:
res += word1[i]
res += word2[i]
i += 1
res += word1[i:] + word2[i:]
return res