- 字符串的最大公因子
对于字符串 S 和 T,只有在 S = T + … + T(T 与自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。
返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。
示例 1:
输入:str1 = “ABCABC”, str2 = “ABC”
输出:“ABC”
示例 2:
输入:str1 = “ABABAB”, str2 = “ABAB”
输出:“AB”
示例 3:
输入:str1 = “LEET”, str2 = “CODE”
输出:""
提示:
1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1[i] 和 str2[i] 为大写英文字母
思路:
求出字符串长度上的最大公因子,根据长度提取字符串前缀,判断前缀是否相等以及每个字符串是否由前缀组成。
class Solution(object):
def gcdOfStrings(self, str1, str2):
if len(str1) < len(str2):
str1, str2 = str2, str1#将短的字符串赋给str2
len_str1 = m = len(str1)
len_str2 = n = len(str2)
res = ''
while n > 0:
m, n = n, m%n#辗转相除法求最大公因子
gcd = m
rep1, rep2 = str1[:gcd], str2[:gcd]
#判断最大公因子对应的前缀是否相等,以及是否能构成字符串str1和str2
if rep1 == rep2 and str1 == rep1*(len_str1//gcd ) and str2 == len_str2//gcd*rep2:
return rep1
return res