""" 1071.1 - Solution 1 - GCD of Lengths (Optimal) """
#####################################################################################
# Imports
#####################################################################################
from math import gcd
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def gcdOfStrings(self, str1: str, str2: str) -> str:
"""Greatest Common Divisor of Strings Function"""
if str1 + str2 != str2 + str1:
return ""
return str1[:gcd(len(str1), len(str2))]
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().gcdOfStrings("ABCABC", "ABC")) # "ABC"
print(Solution().gcdOfStrings("ABABAB", "ABAB")) # "AB"
print(Solution().gcdOfStrings("LEET", "CODE")) # ""
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()
""" 1071.2 - Solution 2 - Brute Force Check All Prefixes """
#####################################################################################
# Imports
#####################################################################################
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def gcdOfStrings(self, str1: str, str2: str) -> str:
"""Greatest Common Divisor of Strings Function"""
for i in range(min(len(str1), len(str2)), 0, -1):
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 ""
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().gcdOfStrings("ABCABC", "ABC")) # "ABC"
print(Solution().gcdOfStrings("ABABAB", "ABAB")) # "AB"
print(Solution().gcdOfStrings("LEET", "CODE")) # ""
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()