Skip to content

Commit 77f53db

Browse files
Add 'Merge Strings Alternately'
1 parent be5869f commit 77f53db

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ A collection of LeetCode solutions
5858

5959
[Merge k Sorted Lists](./src/merge_k_sorted_lists.py)
6060

61+
[Merge Strings Alternately](./src/merge_strings_alternately.py)
62+
6163
[Merge Two Sorted Lists](./src/merge_two_sorted_lists.py)
6264

6365
[Middle of the Linked List](./src/middle_of_the_linked_list.py)

src/merge_strings_alternately.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
1768. Merge Strings Alternately
3+
4+
https://leetcode.com/problems/merge-strings-alternately
5+
6+
NOTES
7+
* Simple two pointer algorithm.
8+
9+
Slight optimization: You don't actually need the variable `i`.
10+
11+
```
12+
res += word1[p1] + word2[p2]
13+
p1 += 1
14+
p2 += 1
15+
```
16+
"""
17+
18+
19+
class Solution:
20+
def mergeAlternately(self, word1: str, word2: str) -> str:
21+
p1, p2, i = 0, 0, 0
22+
res = ""
23+
24+
while p1 < len(word1) and p2 < len(word2):
25+
if i % 2 == 0:
26+
res += word1[p1]
27+
p1 += 1
28+
else:
29+
res += word2[p2]
30+
p2 += 1
31+
i += 1
32+
33+
while p1 < len(word1):
34+
res += word1[p1]
35+
p1 += 1
36+
37+
while p2 < len(word2):
38+
res += word2[p2]
39+
p2 += 1
40+
41+
return res
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
"""
2+
1768. Merge Strings Alternately
3+
4+
https://leetcode.com/problems/merge-strings-alternately
5+
"""
6+
7+
from unittest import TestCase
8+
9+
from src.merge_strings_alternately import Solution
10+
11+
12+
class TestSolution(TestCase):
13+
def test_1(self):
14+
exp = "apbqcr"
15+
assert Solution().mergeAlternately("abc", "pqr") == exp
16+
17+
def test_2(self):
18+
exp = "apbqrs"
19+
assert Solution().mergeAlternately("ab", "pqrs") == exp
20+
21+
def test_3(self):
22+
exp = "apbqcd"
23+
assert Solution().mergeAlternately("abcd", "pq") == exp

0 commit comments

Comments
 (0)