File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ import unittest
2+
3+ # https://leetcode.com/problems/merge-strings-alternately/
4+
5+
6+ class Solution :
7+ """The intuition behind this problem is simple:
8+ 1) Use two pointers to track what is the current letter from each strings
9+ 2) Loop while each pointer is less than its pointer size
10+ 3) Append the string with letters in the order: word1 then word2
11+ 4) Return the result string
12+ """
13+
14+ def mergeAlternately (self , word1 : str , word2 : str ) -> str :
15+ word1Size = len (word1 )
16+ word2Size = len (word2 )
17+ word1Pointer = 0
18+ word2Pointer = 0
19+
20+ res = ""
21+
22+ while word1Pointer < word1Size or word2Pointer < word2Size :
23+ if word1Pointer < word1Size :
24+ res += word1 [word1Pointer ]
25+ word1Pointer += 1
26+
27+ if word2Pointer < word2Size :
28+ res += word2 [word2Pointer ]
29+ word2Pointer += 1
30+
31+ return res
32+
33+
34+ class Tests (unittest .TestCase ):
35+ def test_one (self ):
36+ word1 = "abc"
37+ word2 = "pqr"
38+
39+ self .assertEqual (Solution ().mergeAlternately (word1 , word2 ), "apbqcr" )
40+
41+ def test_two (self ):
42+ word1 = "ab"
43+ word2 = "pqrs"
44+
45+ self .assertEqual (Solution ().mergeAlternately (word1 , word2 ), "apbqrs" )
46+
47+
48+ if __name__ == "__main__" :
49+ unittest .main ()
Original file line number Diff line number Diff line change 3838| 1710.py | | |
3939| 1742.py | | |
4040| 1748.py | | |
41+ | 1768.py | String / Two pointers | < https://leetcode.com/problems/merge-strings-alternately > |
4142| 1832.py | | |
4243| 1859.py | | |
4344| 1876.py | | |
You can’t perform that action at this time.
0 commit comments