ปัญหา
ให้สตริง s, t, r ต้องการตรวจสอบว่า r = s + t หรือ r = t + s
ตัวอย่าง
s = "world", t = "hello", r = "helloworld" → r = t + s → True
แนวคิดการแก้ปัญหา
- ถ้าความยาว r ≠ len(s) + len(t) →
False - ตรวจสอบว่า r เริ่มต้นด้วย s และจบด้วย t →
True - ตรวจสอบว่า r เริ่มต้นด้วย t และจบด้วย s →
True - มิฉะนั้น →
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