มี String s ต้องเช็คว่าแยกเป็น 4 Substring ไม่ว่าง และ Unique ทุกตัวได้หรือไม่
เช่น Input s = "helloworld" Output True (เช่น ["hel","lo","wor","ld"])
ขั้นตอนแก้:
- ถ้า len(s) >= 10 Return True (Pigeonhole Principle: 10 ตัวอักษร สร้าง 4 Unique ได้เสมอ)
- Brute Force 3 Cut Points i,j,k (Nested Loops) ตัด Substring 4 ส่วน เช็ค Unique
ตัวอย่างโค้ด
def solve(s):
if len(s) >= 10:
return True
for i in range(1, len(s)):
for j in range(i + 1, len(s)):
for k in range(j + 1, len(s)):
sub1 = s[0:i]
sub2 = s[i:j]
sub3 = s[j:k]
sub4 = s[k:]
if sub1 != sub2 and sub1 != sub3 and sub1 != sub4 and sub2 != sub3 and sub2 != sub4 and sub3 != sub4:
return True
return False
s = "helloworld"
print(solve(s))
Input
"helloworld"
Output
True