ปัญหา
สตริง s ประกอบด้วย 'a', 'b', 'c' เท่านั้น ดำเนินการซ้ำ: เลือก prefix ที่ตัวอักษรเหมือนกัน และ suffix ที่ตัวอักษรเหมือนกัน (prefix และ suffix ไม่ทับซ้อน และตัวอักษรต้องเหมือนกัน) ลบทั้งคู่ออก หาความยาวน้อยที่สุดของ s หลังดำเนินการได้ไม่จำกัดครั้ง
ตัวอย่าง
s = "aabccabba" → ผลลัพธ์ 3 (ลบ "aa" และ "a" เหลือ "bccabb", ลบ "b" และ "bb" เหลือ "cca" ยาว 3)
ขั้นตอนการแก้ปัญหา
s := deque(s)- بينما
len(s) > 1 and s[0] == s[-1]:chk := s[0]- بينما
s and s[0] == chk:s.popleft() - بينما
s and s[-1] == chk:s.pop()
- คืน
len(s)
การนำไปใช้งาน (Python)
from collections import deque
def solve(s):
s = deque(s)
while len(s) > 1 and s[0] == s[-1]:
chk = s[0]
while s and s[0] == chk:
s.popleft()
while s and s[-1] == chk:
s.pop()
return len(s)
s = "aabccabba"
print(solve(s))
อินพุต
"aabccabba"
เอาต์พุต
3