Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình kiểm tra chuỗi lặp lại trong Python


Cho chuỗi, kiểm tra có phải là chuỗi lặp lại (gồm một chuỗi con lặp lại nhiều lần) hay không.

Ví dụ: → True (lặp "helloworld" 2 lần).

Giải thuật (Kiểm tra ước số độ dài)

  1. Tìm tất cả ước số của .
  2. Với mỗi ước : lấy tiền tố .
  3. Nếu → trả về .
  4. Trả về .

Ví dụ minh họa

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]
            val = s.count(ss)
            if val == n // i:
                return True
        return False

ob = Solution()
print(ob.solve("helloworldhelloworld"))  # Output: True

Đầu vào

"helloworldhelloworld"

Đầu ra

True