ปัญหา
ให้สตริง s และ pattern t (ไม่มีตัวซ้ำ) ตรวจสอบว่าตัวอักษรใน s ปรากฏตามลำดับเดียวกับใน t หรือไม่
ตัวอย่าง
s = "hello world", t = "hw" → 'h' อยู่ก่อน 'w' ใน s → True
แนวคิดการแก้ปัญหา
- สำหรับคู่ตัวอักษรติดกันใน t (x, y)
- หาตำแหน่งสุดท้ายของ x ใน s (
rindex) - หาตำแหน่งแรกของ y ใน s (
index) - ต้องมี last_x < first_y
โค้ดตัวอย่าง
def solve(s, t):
if len(s) < len(t):
return False
for i in range(len(t) - 1):
x, y = t[i], t[i+1]
last_x = s.rfind(x)
first_y = s.find(y)
if last_x == -1 or first_y == -1 or last_x > first_y:
return False
return True
print(solve("hello world", "hw")) # True
อินพุต / เอาต์พุต
Input: "hello world", "hw" Output: True