假设有两个字符串A和B。可以说当A通过一次或多次串联创建A时,A可被B整除。因此,如果A =“ abcabc”,而B =“ abc”,则A可被B整除。在本节中,我们将看到字符串的最大公约数是什么。因此,返回将两个字符串分开的最大字符串。因此,如果两个字符串分别是“ ABABAB”和“ ABAB”,则GCD将为“ AB”
为了解决这个问题,我们将遵循以下步骤-
temp:= A和B之间的较短字符串
m:=温度长度
x:= 1
res是一个数组,在“ res”中插入“”
而A和B的子字符串大小为x,则将该子字符串添加到res中,并将x增大1
最后返回res数组中的最后一个元素。
让我们看下面的实现以更好地理解-
class Solution(object):
def gcdOfStrings(self, str1, str2):
if len(str1)<=len(str2):
temp = str1
else:
temp = str2
m = len(temp)
x = 1
res=[""]
while x<=m:
if m%x==0 and temp[:x] * (len(str1)//x) == str1 and temp[:x] * (len(str2)//x) == str2:
res.append(temp[:x])
x+=1
return res[-1]
ob1 = Solution()print(ob1.gcdOfStrings("ABABAB","ABAB"))"ABABAB" "ABAB"
输出结果
AB