-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
1768. Merge Strings Alternately Leet Code #106
- Loading branch information
1 parent
4460389
commit 32476e2
Showing
2 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
18 changes: 18 additions & 0 deletions
18
Algorithms/LeetCode.Algorithms.Tests/M/Merge Strings Alternately.Tests.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
35 changes: 35 additions & 0 deletions
35
Algorithms/LeetCode.Algorithms/LeetCode.Algorithms/M/Merge Strings Alternately.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |