Greatest Common Divisor of Strings LeetCode solution in Python

1
# Runtime: 85 ms (Top 15.89%) | Memory: 14 MB (Top 5.19%)
2
class Solution:
3
def gcdOfStrings(self, str1: str, str2: str) -> str:
4

5
if len(str2) > len(str1):
6
str1, str2 = str2, str1
7

8
curr_str2 = str2
9
while True:
10

11
rep = len(str1) // len(curr_str2)
12

13
if curr_str2 * rep == str1:
14
return curr_str2
15

16
found = False
17
for i in range(len(curr_str2) - 1, 1, -1):
18
try_str2 = curr_str2[:i]
19
rep2 = len(str2) // len(try_str2)
20

21
if try_str2 * rep2 == str2:
22
curr_str2 = try_str2
23
found = True
24
break
25

26
if not found:
27
break
28
return ""

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0