กำหนดสตริง password ต้องหาจำนวนการเปลี่ยนแปลงขั้นต่ำเพื่อให้รหัสผ่านแข็งแกร่ง โดยมีเกณฑ์:
- ความยาว 6-20 ตัวอักษร
- ต้องมีตัวพิมพ์เล็ก ตัวพิมพ์ใหญ่ และตัวเลข อย่างน้อย 1 ตัว
- ห้ามมีตัวอักษรซ้ำ 3 ตัวติดกัน (เช่น aaa, PPP, 888)
ตัวอย่าง: "aa26bbb" → ต้องเปลี่ยนอย่างน้อย 1 ครั้ง (ไม่มีตัวพิมพ์ใหญ่ และมี b ซ้ำ 3 ตัว)
ขั้นตอนการแก้ปัญหา
- นับ missing_types (lower, upper, digit)
- หา repeating sequences คำนวณ change ที่ต้องทำ
- จัดการกรณีความยาว < 6, 6-20, > 20 แยกกัน
- สำหรับ > 20: คำนวณ delete ที่ต้องลบ และปรับ change ตามเงื่อนไข
ตัวอย่างโค้ด
class Solution(object):
def strongPasswordChecker(self, s):
missing_type = 3
if any('a' <= c <= 'z' for c in s): missing_type -= 1
if any('A' <= c <= 'Z' for c in s): missing_type -= 1
if any(c.isdigit() for c in s): missing_type -= 1
change = 0
one = two = 0
p = 2
while p < len(s):
if s[p] == s[p-1] == s[p-2]:
length = 2
while p < len(s) and s[p] == s[p-1]:
length += 1
p += 1
change += length // 3
if length % 3 == 0: one += 1
elif length % 3 == 1: two += 1
else:
p += 1
if len(s) < 6:
return max(missing_type, 6 - len(s))
elif len(s) <= 20:
return max(missing_type, change)
else:
delete = len(s) - 20
change -= min(delete, one)
change -= min(max(delete - one, 0), two * 2) // 2
change -= max(delete - one - 2 * two, 0) // 3
return delete + max(missing_type, change)
ob = Solution()
print(ob.strongPasswordChecker('aa26bbb'))
อินพุต
"aa26bbb"
เอาต์พุต
1