leetcode 1071. Greatest Common Divisor of GCD Euclidean string Strings
leetcode 2020 March 1 question daily punch
EuclideanSee https://blog.csdn.net/weixin_43973433/article/details/105007066
Title:
For strings S and T, only S = T + ... + T ( T connected to itself one or more times), we identified "T S can be divisible." Returns the longest string X, X can meet the requirements, and X can be divisible divisible str1 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:" "
Tip:
. 1 <= str1.length <= 1000
. 1 <= str2.length <= 1000
str1 [I] and str2 [i] uppercase letters
Ideas:
- If the two strings have the common denominator, then a + b == b + a
- Two string length is equal to the largest common divisor of the two conventions segment length of the string
Code:
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))]
This blog is an original work, welcomed the guidance, reproduced, please indicate the source, attach a link to this article, thank you!