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

ตรวจสอบว่าสตริง r เป็นการต่อท้ายของ s และ t (หรือ t และ s) หรือไม่ ใน Python


ปัญหา

ให้สตริง s, t, r ต้องการตรวจสอบว่า r = s + t หรือ r = t + s

ตัวอย่าง

s = "world", t = "hello", r = "helloworld" → r = t + s → True

แนวคิดการแก้ปัญหา

  1. ถ้าความยาว r ≠ len(s) + len(t) → False
  2. ตรวจสอบว่า r เริ่มต้นด้วย s และจบด้วย t → True
  3. ตรวจสอบว่า r เริ่มต้นด้วย t และจบด้วย s → True
  4. มิฉะนั้น → False

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

def solve(s, t, r):
    if len(r) != len(s) + len(t):
        return False
    if r.startswith(s) and r.endswith(t):
        return True
    if r.startswith(t) and r.endswith(s):
        return True
    return False

s = "world"
t = "hello"
r = "helloworld"
print(solve(s, t, r))  # True

อินพุต / เอาต์พุต

Input:  "world", "hello", "helloworld"
Output: True