สมมติว่าเรามีข้อความสามสตริง w1 และ w2 ข้อความเป็นประโยคที่มีคำต่างกัน เราต้องหาระยะห่างที่เล็กที่สุดระหว่าง w1 และ w2 สองครั้งในข้อความ ระยะทางจะวัดเป็นจำนวนคำระหว่างกัน หากไม่มี w1 หรือ w2 ในข้อความ ให้คืนค่า -1
ดังนั้น หากอินพุตเป็น text ="joy happy power happy joy joy power happy limit" w1 ="power" w2 ="limit" ผลลัพธ์จะเป็น 1 เนื่องจากมีคำเดียว "happy" อยู่ระหว่าง พลังและขีดจำกัด
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
-
index1 :=null, index2 :=null
-
ระยะทาง :=999999
-
สำหรับแต่ละดัชนี idx และ word w ในข้อความ ให้ทำ
-
ถ้า w เหมือนกับ w1 แล้ว
-
ถ้า index2 ไม่เป็นโมฆะ
-
ระยะทาง :=ระยะทางขั้นต่ำและ (|idx - index2| - 1)
-
-
index1 :=idx
-
-
ถ้า w เหมือนกับ w2 แล้ว
-
ถ้า index1 ไม่เป็นโมฆะ
-
ระยะทาง :=ระยะทางขั้นต่ำและ (|idx - index1| - 1)
-
-
index2 :=idx
-
-
-
ถ้า index1 ไม่เป็น null และ index2 ไม่เป็น null ดังนั้น
-
ระยะทางกลับ
-
-
กลับ -1
ตัวอย่าง
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น
def solve(text, w1, w2):
index1 = None
index2 = None
distance = 2000000
for idx, word in enumerate(text.split(" ")):
if word == w1:
if index2 is not None:
distance = min(distance, abs(idx - index2) - 1)
index1 = idx
if word == w2:
if index1 is not None:
distance = min(distance, abs(idx - index1) - 1)
index2 = idx
if index1 is not None and index2 is not None:
return distance
return -1
text = "joy happy power happy joy joy power happy limit"
w1 = "power"
w2 = "limit"
print(solve(text, w1, w2)) อินพุต
"joy happy power happy joy joy power happy limit", "power", "limit"
ผลลัพธ์
1