Python 程序检查字符串是否重复
假设我们有一个字符串,我们需要检查它是否是一个重复字符串。
因此,如果输入类似于 string = "helloworldhelloworld",则输出将为 True
为了解决这个问题,我们将遵循以下步骤:
- n := s 的大小
- 定义一个函数 findFactors()。这将接收 n
- f := 一个新的集合
- i := 1
- 当 i * i <= n 时,执行以下操作:
- 如果 n mod i 等于 0,则:
- 将 (n / i) 的商插入 f
- 将 i 插入 f
- i := i + 1
- 如果 n mod i 等于 0,则:
- 返回 f
- 从主方法中执行以下操作:
- fact := findFactors(n)
- 对于 fact 中的每个 i,执行以下操作:
- 如果 i 等于 n,则:
- 进入下一个迭代
- ss := s[从索引 0 到 i-1]
- val := ss 在 s 中出现的次数
- 如果 val 等于 (n/i) 的商,则:
- 返回 True
- 如果 i 等于 n,则:
- 返回 False
让我们看一下以下实现以更好地理解:
示例
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(int(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 == int(n / i)): return True return False ob = Solution() print(ob.solve("helloworldhelloworld"))
输入
"helloworldhelloworld"
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
True
广告