การลบตัวอักษรซ้ำจากสตริง (เก็บลำดับเดิม)
ลบตัวอักษรที่ซ้ำกันออกไป เก็บเฉพาะครั้งแรกที่ปรากฏ รักษาลำดับเดิม
อัลกอริทึม (ใช้ OrderedDict)
- สร้าง OrderedDict ว่าง d
- วนลูปตัวอักษร c ใน s:
- ถ้า c ไม่อยู่ใน d: d[c] = 0
- d[c] += 1 (นับความถี่ ไม่ใช้ก็ได้)
- รวม keys ของ d ตามลำดับ → สตริงผลลัพธ์
ตัวอย่างโค้ด
from collections import OrderedDict
def solve(s):
d = OrderedDict()
for c in s:
if c not in d:
d[c] = 0
d[c] += 1
return ''.join(d.keys())
s = "bbabcaaccdbaabababc"
print(solve(s))
ผลลัพธ์
"bacd"
วิธีอื่น (Python 3.7+)
# dict ธรรมดาใน Python 3.7+ รักษาลำดับ insertion
def solve(s):
d = {}
for c in s:
if c not in d:
d[c] = 1
return ''.join(d.keys())
# หรือใช้ set แบบ one-liner (แต่ไม่รับประกันลำดับใน Python < 3.7)
# ''.join(dict.fromkeys(s)) # Python 3.7+