对于字符串 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] 为大写英文字母
解法1:
import math
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
l = math.gcd(len(str1), len(str2))
return str1[:l] if str1 + str2 == str2 + str1 else ""
【leetcode-python】1071. 字符串的最大公因子
最新推荐文章于 2024-04-30 22:11:07 发布
本文介绍了一种基于字符串除法概念的独特算法,该算法能够找出两个字符串的最大公共除数字符串。通过实例展示了如何使用数学中的最大公约数概念来确定最长的字符串X,使得X既能整除str1也能整除str2。

645

被折叠的 条评论
为什么被折叠?



