For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t (that is, t is concatenated with itself one or more times to form s).
Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.
Function Signature
def gcd_of_strings(str1: str, str2: str) -> str:
Rules
-
"Largest" means longest. When a common divisor exists, the longest one is unique.
-
x
must be nonempty. If no nonempty string divides both
str1
and
str2
, return the empty string
""
.
Constraints
-
1 <= len(str1), len(str2) <= 1000
-
str1
and
str2
consist of uppercase English letters.
Examples
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
"ABC" repeated 2 times gives "ABCABC" and repeated 1 time gives "ABC". No longer string divides "ABC", so it is the largest.
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
"AB" divides "ABABAB" (3 times) and "ABAB" (2 times). "ABAB" does not divide "ABABAB" because 6 is not a multiple of 4.
Input: str1 = "ABCDEF", str2 = "ABC"
Output: ""
A common divisor must have length 1 or 3, since its length divides both 6 and 3. "ABC" repeated twice is "ABCABC", not "ABCDEF", and "A" does not divide "ABC". No common divisor exists.