Date and Time: Sep 13, 2024, 22:00 (EST)
Link: https://leetcode.com/problems/greatest-common-divisor-of-strings/
For two strings s
and t
, we say "t
divides s
" if and only if s = t + t + t + ... + t + t
(i.e., t
is concatenated with itself one or more times).
Given two strings str1
and str2
, return the largest string x
such that x
divides both str1
and 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: ""
-
1 <= str1.length, str2.length <= 1000
-
str1
andstr2
consist of English uppercase letters.
-
We can loop over the
min(len(str1), len(str2))
backward because we want to find the largest string prefix, and we slice a prefix fromstr1
orstr2
, then we first compare if the length of this prefix is divisible bystr1
andstr2
, so we know this prefix can concatenate these two strings. -
If we find a prefix, we then use this prefix from either
str1
orstr2
(not both) and compare if we multiply the same prefix multiple times, can we get the originalstr1
andstr2
back. If so, we can return the prefixstr1[:i]
, because we start backward, which will be the largest string. Otherwise, we return""
in the end.
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
# Try a prefix and then time its muliplication and see if it matches
# From the back so we know the largest string
for i in range(min(len(str1), len(str2)), 0, -1):
if len(str1) % len(str1[:i]) == 0 and len(str2) % len(str2[:i]) == 0:
if str1[:i] * (len(str1) // i) == str1 and str1[:i] * (len(str2) // i) == str2:
return str1[:i]
return ""
Time Complexity: m
is length of str1
, n
is length of str2
.
Space Complexity: