Leetcode daily 20/03/12 字符串的最大公因子
字符串的最大公因子
-题目-
对于字符串 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-
如果两个字符串长度相等,它们只可能是相同或不符合题目条件两种情况。
如果两个字符串长度不相等,从较短字符串由长到短不断截取字串X
。只要字串X
满足:
X
的长度能整除两个字符串的长度;X
重复len(str1) / len(x)
次和str1
相等;X
重复len(str2) / len(x)
次和str2
相等;
则X
是结果。
-ac代码-
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
# If the lens are equal, the strs may be the same or not satisfy the requirements.
if len(str1) == len(str2):
return str1 if str1 == str2 else ""
# Finds the shorter and the longer.
short_str, long_str = (str1, str2) if len(str1) < len(str2) else (str2, str1)
for i in range(len(short_str), 0, -1):
X = short_str[:i]
if len(short_str) % len(X) == 0 and len(long_str) % len(X) == 0 \
and X * int(len(str1) / len(X)) == str1 \
and X * int(len(str2) / len(X)) == str2:
return X
return ""
-复杂度-
- \(T(n) = O(len(short\_str))\) (取较短字符串字串次数)
- \(S(n) = O(len(str1) + len(str2))\) (用
X
构造两个分别和str1和str2长度相等的字符串)
-笔记-
- python-笔记:从右到左遍历序列:
range(-1, len(seq) - 1, -1)
。 - python-笔记:
a, b = (a, b) if condition else (b, a)
。需要括号。