หา Substring ทั้งหมดที่มีความยาว N และมีตัวอักษรที่ต่างกัน (Distinct) อยู่ K ตัว โดยใช้ set() นับ Unique Characters
ตัวอย่างโค้ด
my_string = 'Pythonisfun'
print("The string is : ")
print(my_string)
my_substring = 2
my_chars = 2
my_result = []
for idx in range(0, len(my_string) - my_substring + 1):
if len(set(my_string[idx: idx + my_substring])) == my_chars:
my_result.append(my_string[idx: idx + my_substring])
print("The resultant string is : ")
print(my_result)
ผลลัพธ์
The string is : Pythonisfun
The resultant string is : ['Py', 'yt', 'th', 'ho', 'on', 'ni', 'is', 'sf', 'fu', 'un']
คำอธิบาย
- Sliding Window:
my_string[idx:idx+N]ดึง Substring ความยาว N set(substring)สร้าง Set ของตัวอักษร (Unique)len(set) == Kเช็คว่ามี Distinct Characters เท่ากับ K- N=2, K=2 -> หาคู่ตัวอักษรที่ไม่ซ้ำกันติดกัน