GDC, Greatest Common Divisor.
1st.
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
#get the same string on str1 and str2 and print
result =""
i,j = 0,0
while i < len(str1) and j < len(str2):
result = str1[i]
result = str2[j]
i += 1
j += 1
result += str1[i:]
result += str2[j:]
return result
I thought I could get through this coding test by using the same code we used last time. I was not sure how to write the prefix part, so I asked AI, but I could not get the correct answer.
I tried editing the code several times but I could not pass this test case.
Input
str1 =
"ABABAB"
str2 =
"ABAB"
Output
"AB"
Expected
"AB"
This comment helped me.
https://leetcode.com/problems/greatest-common-divisor-of-strings/description/comments/1782570
I learned that it is better to divide a given string evenly.
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
if str1 == str2:
return str1
# Find the length of the shorter string
n = min(len(str1), len(str2))
# Iterate over candidate string lengths
for i in range(n, 0, -1):
# Check if the candidate string is a divisor of both strings
if len(str1) % i == 0 and len(str2) % i == 0:
candidate = str1[:i]
if candidate * (len(str1) // i) == str1 and candidate * (len(str2) // i) == str2:
return candidate
return ""
Top comments (0)