Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมรวมสตริงสลับกันด้วย Python


สมมติว่าเรามีสตริง s และ t เราต้องรวมพวกเขาโดยสลับตัวอักษรเริ่มจาก s ถ้า s และ t ความยาวไม่เท่ากัน ให้เติมตัวอักษรที่เหลือต่อท้าย

เช่น s = "major" t = "general" ผลลัพธ์คือ "mgaejnoerral" เพราะ t ยาวกว่า เติม "ral" ท้าย

ขั้นตอนการแก้ปัญหา

  • i = j = 0, result = ""
  • while i < len(s) และ j < len(t):
    • result += s[i] + t[j]
    • i++, j++
  • while i < len(s): result += s[i]; i++
  • while j < len(t): result += t[j]; j++
  • คืน result

ตัวอย่างโค้ด

def solve(s, t):
    i = j = 0
    result = ""
    while i < len(s) and j < len(t):
        result += s[i] + t[j]
        i += 1
        j += 1
    while i < len(s):
        result += s[i]
        i += 1
    while j < len(t):
        result += t[j]
        j += 1
    return result

s = "major"
t = "general"
print(solve(s, t))

ข้อมูลเข้า

"major", "general"

ข้อมูลออก

mgaejnoerral