|
This post is completed by 2 users
|
Add to List |
562. Merge Strings Alternately - Leetcode
Problem Statement
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If one string is longer than the other, append the additional letters onto the end of the merged string.
Constraints:
1 <= word1.length, word2.length <= 100word1andword2consist of lowercase English letters.
Examples
Input: word1 = abc, word2 = pqr Output: apbqcr
Input: word1 = abcd, word2 = pq Output: apbqrs
Input: word1 = ab, word2 = pqrs Output: apbqcd
Solution
- Initialize an empty list
mergedto store the resulting characters. - Use two pointers
iandjto track positions inword1andword2. - Iterate through
word1andword2simultaneously, appending characters alternately. - If any characters remain in
word1orword2, append them directly to the result. - Convert the list to a string and return the result.
Complexity Analysis
- Time Complexity: O(n + m), where
nandmare the lengths ofword1andword2, respectively. We iterate through both strings once. - Space Complexity: O(n + m), since we store the merged string in a list before joining.