LeetCode 75
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.برای حل این مسئله، باید دو رشته رو به صورت یکیدرمیون ترکیب کنیم. یعنی از هر رشته یک کاراکتر برداریم و به نتیجه اضافه کنیم. اگر یکی از رشتهها زودتر تموم شد، بقیهی کاراکترهای رشتهی دیگه رو همونطور که هست به انتهای نتیجه اضافه میکنیم.
بیایم قدمبهقدم فکر کنیم:
word1
و یکی از word2
رو به خروجی اضافه میکنیم.حالا که الگوریتم رو فهمیدیم، بیایم تبدیلش کنیم به کد پایتون:
for
استفاده میکنیم که به تعداد کوتاهترین رشته اجرا بشه.result
که توش کاراکترها رو ذخیره میکنیم.for
، بقیهی رشتهی بلندتر رو اضافه میکنیم.کد:
def mergeAlternately(word1, word2):
result = []
min_length = min(len(word1), len(word2))
# یکیدرمیون حروف رو اضافه کن
for i in range(min_length):
result.append(word1[i])
result.append(word2[i])
# اگر یکی از رشتهها طولانیتره، ادامهش رو اضافه کن
result.append(word1[min_length:])
result.append(word2[min_length:])
return "".join(result)
#علی برادر خدام خسروشاهی
list
خالی به اسم result
برای ذخیرهی جواب میسازیم.word1
و word2
رو پیدا میکنیم تا بدونیم چند بار باید یکیدرمیون اضافه کنیم.for
حلقه میزنیم و از هر کدوم یه کاراکتر برمیداریم و به result
اضافه میکنیم.result
اضافه میکنیم.result
رو به یک رشته تبدیل کرده و برمیگردونیم.result.append(word1[min_length:])
از slicing استفاده کردیم که خیلی تمیز و سریع کار میکنه و بقیهی حروف باقیمونده رو اضافه میکنه.result
یه لیسته، در نهایت با "".join(result)
اون رو به یک رشتهی نهایی تبدیل میکنیم.حالا که کد رو فهمیدی، میتونی خودت یه مثال جدید تست کنی؟ 😉
علی برادر خدام خسروشاهی