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

ตรวจสอบว่าสตริงปฏิบัติตามลำดับตัวอักษรใน pattern หรือไม่ ใน Python


ปัญหา

ให้สตริง s และ pattern t (ไม่มีตัวซ้ำ) ตรวจสอบว่าตัวอักษรใน s ปรากฏตามลำดับเดียวกับใน t หรือไม่

ตัวอย่าง

s = "hello world", t = "hw" → 'h' อยู่ก่อน 'w' ใน s → True

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

  1. สำหรับคู่ตัวอักษรติดกันใน t (x, y)
  2. หาตำแหน่งสุดท้ายของ x ใน s (rindex)
  3. หาตำแหน่งแรกของ y ใน s (index)
  4. ต้องมี 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