Q:
对于字符串 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"
链接:https://leetcode-cn.com/problems/greatest-common-divisor-of-strings/
思路:暴力求解
代码:
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
if len(str1) > len(str2):
s1, s2 = str1, str2
else:
s2, s1 = str1, str2
if s1.replace(s2,'') == '':
return s2
i = len(s2)
while i <= len(s2) and i != 0:
temp1 = s1
temp2 = s2
if temp1.replace(s2[:i],'') == '' and temp2.replace(s2[:i],'') == '':
return s2[:i]
else:
i-=1
return ''