Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมตรวจสอบว่าสตริงเป็น Repeating String หรือไม่ใน Python

สมมติว่าเรามีสตริง ต้องตรวจสอบว่ามันเป็น repeating string (ประกอบด้วย substring ซ้ำๆ) หรือไม่

ตัวอย่าง: "helloworldhelloworld" → True (ซ้ำ "helloworld" 2 ครั้ง)

ขั้นตอนการแก้ปัญหา (Factor-based Check)

  1. n = len(s)
  2. หาตัวหารทั้งหมดของ n (factor pairs)
  3. สำหรับแต่ละ factor i (ยกเว้น n เอง):
    • ss = s[:i] (substring 候選)
    • นับจำนวน ss ใน s
    • หากเท่ากับ n/i → True
  4. คืนค่า 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