Skip to content

Commit

Permalink
1768. Merge Strings Alternately Leet Code #106
Browse files Browse the repository at this point in the history
  • Loading branch information
AhmedKhalil777 committed Sep 22, 2023
1 parent 4460389 commit 32476e2
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeetCode.Algorithms.Tests;

public class Merge_Strings_Alternately
{
[Theory]
[InlineData("abc", "pqr", "apbqcr")]
[InlineData("ab", "pqrs", "apbqrs")]
public void MergeAlternately(string word1, string word2, string res)
{
new Algorithms.Merge_Strings_Alternately().MergeAlternately(word1, word2).Should().Be(res);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System.Text;

namespace LeetCode.Algorithms;

public class Merge_Strings_Alternately
{
public string MergeAlternately(string word1, string word2)
{
if (word1.Length == 0)
{
return word2;
}
if (word2.Length ==0)
{
return word1;
}
var sb = new StringBuilder();
var minLength = word1.Length < word2.Length ? word1.Length : word2.Length;
for (int i = 0; i < minLength; i++)
{

sb.Append(word1[i]);
sb.Append(word2[i]);
if (i+1 == word1.Length)
{
sb.Append(word2[(i+1)..(word2.Length)]);
}
if (i + 1 == word2.Length)
{
sb.Append(word1[(i+1)..(word1.Length)]);
}
}
return sb.ToString();
}
}

0 comments on commit 32476e2

Please sign in to comment.