[leetcode] 1071. Greatest Common Divisor of Strings
原创
©著作权归作者所有:来自51CTO博客作者是念的原创作品,请联系作者获取转载授权,否则将追究法律责任
Description
For two strings s and t, we say “t divides s” if and only if s = t + … + t (t concatenated with itself 1 or more times)
Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.
Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:
Input: str1 = "LEET", str2 = "CODE"
Output: ""
Example 4:
Input: str1 = "ABCDEF", str2 = "ABC"
Output: ""
Constraints:
- 1 <= str1.length <= 1000
- 1 <= str2.length <= 1000
- str1 and str2 consist of English uppercase letters.
分析
题目的意思是:给定两个字符串str1,str2.求字符串的最大公约字符串。这道题我的思路是从短的字符串找公约字符串,然后看是否满足长字符串的要求,也能做出来,但是思路不是很好。一个更好的思路是类似求最大公约数的方式进行递归求解,如代码二。
代码一
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
m=len(str1)
n=len(str2)
if(m>n):
str1,str2=str2,str1
for i in range(n,-1,-1):
t=str1[:i]
t1=str1.replace(t,'')
t2=str2.replace(t,'')
if(t1==t2 and t1==''):
return t
return ''
代码二
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
m=len(str1)
n=len(str2)
if(m<n):
return self.gcdOfStrings(str2,str1)
if(str1[:n]==str2):
if(m==n):
return str2
return self.gcdOfStrings(str2,str1[n:])
return ''
参考文献
[LeetCode] Python Solution | Euclid’s algorithm | 10 lines | Time Complexity -> 95 % | Space Complexity -> 100%