leetcode 1071. Greatest Common Divisor of Strings 字符串的最大公因子 辗转相除法
leetcode 2020年3月 每日一题打卡
辗转相除法请看https://blog.csdn.net/weixin_43973433/article/details/105007066
题目:
对于字符串 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] 为大写英文字母
思路:
- 如果两个字符串有最大公约数,则a+b == b+a
- 两字符串最大公约段的长度等于两字符串长度的最大公约数
代码:
class Solution(object):
def gcdOfStrings(self, str1, str2):
"""
:type str1: str
:type str2: str
:rtype: str
"""
# 如果两个字符串有最大公约数,则a+b == b+a
if str1+str2 != str2+str1:
return ""
# 两字符串最大公约段的长度等于两字符串长度的最大公约数
# 辗转相除法
def gcd(m,n):
return gcd(n,m%n) if n else m
return str1[:gcd(len(str1),len(str2))]
本博客为原创作品,欢迎指导,转载请说明出处,附上本文链接,谢谢!