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

หาตัวอักษรในสตริงแรกที่อยู่ดัชนีน้อยที่สุดในสตริงที่สองใน Python

สมมติว่าเรามีสตริง str และ patt ต้องการหาตัวอักษรใน patt ที่ปรากฏใน str ด้วยดัชนีน้อยที่สุด หากไม่มีตัวอักษรใดใน patt อยู่ใน str คืนค่า -1

เช่น str = "helloworld", patt = "wor" ผลลัพธ์คือ 'o' (อยู่ดัชนี 4 ใน str)

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

  1. สร้างแผนที่เก็บดัชนีแรกของแต่ละตัวอักษรใน str
  2. วนลูปตัวอักษรใน patt หาตัวที่มีดัชนีน้อยที่สุด

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

def get_min_index_char(Str, patt):
    first_index = {}
    for i, ch in enumerate(Str):
        if ch not in first_index:
            first_index[ch] = i
    min_idx = float('inf')
    ans = -1
    for ch in patt:
        if ch in first_index and first_index[ch] < min_idx:
            min_idx = first_index[ch]
            ans = ch
    return ans if ans != -1 else -1

Str = "helloworld"
patt = "wor"
print(get_min_index_char(Str, patt))

อินพุต

"helloworld", "wor"

เอาต์พุต

o