用 Python 检查字符串是否为重复字符串的程序
pythonserver side programmingprogramming更新于 2026/1/12 21:00:17
假设我们有一个字符串,我们必须检查它是否是重复字符串。
因此,如果输入为 string = "helloworldhelloworld",则输出将为 True
为了解决这个问题,我们将遵循以下步骤 −
- n := size of s
- 定义一个函数 findFactors() 。这将需要 n
- f := a new set
- 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)
- 对于每个 i,实际上,执行
- 如果 i 与 n 相同,则
- 进行下一个迭代
- ss := s[从索引 0 到 i-1]
- val := s 中 ss 的出现次数
- 如果 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"
输出
True
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

