สมมติว่าเรามีสตริง ต้องตรวจสอบว่ามันเป็น repeating string (ประกอบด้วย substring ซ้ำๆ) หรือไม่
ตัวอย่าง: "helloworldhelloworld" → True (ซ้ำ "helloworld" 2 ครั้ง)
ขั้นตอนการแก้ปัญหา (Factor-based Check)
n = len(s)- หาตัวหารทั้งหมดของ n (factor pairs)
- สำหรับแต่ละ factor
i(ยกเว้น n เอง):ss = s[:i](substring 候選)- นับจำนวน
ssในs - หากเท่ากับ
n/i→ True
- คืนค่า False
ตัวอย่างโค้ด Python
class Solution:
def solve(self, s):
n = len(s)
def findFactors(n):
f = set()
i = 1
while i * i <= n:
if n % i == 0:
f.add(n // i)
f.add(i)
i += 1
return f
fact = findFactors(n)
for i in fact:
if i == n:
continue
ss = s[:i]
if s.count(ss) == n // i:
return True
return False
ob = Solution()
print(ob.solve("helloworldhelloworld")) # Output: True
อินพุต
"helloworldhelloworld"
เอาต์พุต
True