Created
October 9, 2024 15:03
-
-
Save hongtaoh/fbc653c3359167e004639ed70f990353 to your computer and use it in GitHub Desktop.
Solution to Leetcode 1071 Greatest Common Divisor of Strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
# the most straightforward implementation | |
def gcdOfStrings(self, str1: str, str2: str) -> str: | |
short_str, long_str = (str1, str2) if len(str1) <= len(str2) else (str2, str1) | |
l = 0 | |
while l < len(short_str): | |
r = len(short_str) | |
while r >l and r <= len(short_str): | |
substr = short_str[l:r] | |
substr_len = r - l | |
if len(short_str) % substr_len == 0 and len(long_str) % substr_len == 0: | |
k_short = len(short_str) // substr_len | |
k_long = len(long_str) // substr_len | |
if short_str == substr * k_short and long_str == substr * k_long: | |
return substr | |
r -= 1 | |
l += 1 | |
return "" | |
Another version:
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
if str1+str2 != str2+str1:
return ""
# make sure len(str1) >= len(str2)
str1, str2 = (str1, str2) if len(str1)>=len(str2) else (str2, str1)
l=0
while l < len(str2):
r = len(str2)
while r > l:
substr_len = r - l
if len(str1) % substr_len == 0 and len(str2) % substr_len == 0:
return str2[l:r]
r -= 1
l += 1
A even better solution:
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
# check prefix
if str1+str2 != str2+str1:
return ""
# make sure len(str1) >= len(str2)
str1, str2 = (str1, str2) if len(str1)>=len(str2) else (str2, str1)
n = len(str2)
for length in range(n, 0, -1):
if n % length == 0 and len(str1) % length == 0:
return str2[:length]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Utilizing math properties: