1071.Greatest Common Divisor of Strings
My code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
ans = ''
max_len = max(len(str1),len(str2))
min_len = min(len(str1),len(str2))
gcd = 0
for i in range(1,min_len + 1):
if max_len % i == 0 and min_len % i == 0:
gcd = i
if str1[:gcd] * (len(str1) // gcd) == str1 and str1[:gcd] * (len(str2) // gcd) == str2:
ans = str1[:gcd]
return ans
best code
1
2
3
4
5
6
7
8
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
# Check if concatenated strings are equal or not, if not return ""
if str1 + str2 != str2 + str1:
return ""
# If strings are equal than return the substring from 0 to gcd of size(str1), size(str2)
from math import gcd
return str1[:gcd(len(str1), len(str2))]