[
string
math
]
Leetcode 1071. Greatest Common Divisor of Strings
Problem statement
https://leetcode.com/problems/greatest-common-divisor-of-strings/
Solution
First, we check if s1 + s2 == s2 + s1
, in this case we know that gcd
is not empty. If it is not empty, it is equal to gcd of lengths.
Complexity
It is O(n)
for time and space.
Code
class Solution:
def gcdOfStrings(self, s1, s2):
return s1[:gcd(len(s1), len(s2))] if s1 + s2 == s2 + s1 else ""