1768. Merge Strings Alternately
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.
Example 1:
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r
Example 2:
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s
Example 3:
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1: a b c d
word2: p q
merged: a p b q c d
Constraints:
- 1 <= word1.length, word2.length <= 100
- word1 and word2 consist of lowercase English letters.
https://youtu.be/LECWOvTo-Sc?si=3GxC3IS6WPGVq43t
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
idx1, idx2 = 0, 0
res = []
while idx1 < len(word1) and idx2 < len(word2):
res.append(word1[idx1])
res.append(word2[idx2])
idx1 +=1
idx2 +=1
res.append(word1[idx1:])
res.append(word2[idx2:])
return ''.join(res)
'LeetCode > LeetCode75' 카테고리의 다른 글
[LeetCode 75] Easy - 1431. Kids With the Greatest Number of Candies (0) | 2024.11.11 |
---|---|
[LeetCode 75] Medium - 1071. Greatest Common Divisor of Strings ☆ (0) | 2024.11.11 |
[LeetCode 75] Medium - 901. Online Stock Span (4) | 2024.11.10 |
[LeetCode 75] Medium - 739. Daily Temperatures (0) | 2024.11.10 |
[LeetCode 75] Medium - 435. Non-overlapping Intervals (0) | 2024.11.10 |