1768. Merge Strings Alternately
EasyView on LeetCode
Time: O(m+n)
Space: O(m+n)
Advertisement
Intuition
Merge two strings alternately: take one character from each string in turns.
Algorithm
- 1Two pointers i=0, j=0. Alternate appending word1[i] and word2[j]. Append remaining characters.
Common Pitfalls
- •When one string runs out, append remaining characters of the other.
1768.cs
C#
// Approach: Two-pointer alternating append, then append remainder of whichever string is longer.
// Time: O(m+n) Space: O(m+n)
public class Solution
{
public string MergeAlternately(string word1, string word2)
{
int l1 = 0, l2 = 0;
int r1 = word1.Length;
int r2 = word2.Length;
StringBuilder res = new StringBuilder();
while (l1 < r1 && l2 < r2)
{
res.Append(word1[l1++]);
res.Append(word2[l2++]);
}
while (l1 < r1)
res.Append(word1[l1++]);
while (l2 < r2)
res.Append(word2[l2++]);
return res.ToString();
}
}Advertisement
Was this solution helpful?