1071. Greatest Common Divisor of Strings
Problem
String t divides s if s is t repeated one or more times. Return the longest string that divides both str1 and str2, or "" if none does.
Example: "ABCABC", "ABC" → "ABC"; "ABABAB", "ABAB" → "AB"; "LEET", "CODE" → ""
If some string x divides both, then str1 + str2 == str2 + str1 (both are repetitions of x); conversely, when that holds both are repetitions of a common block, and the longest divisor has length gcd(len1, len2).
Complexity: O(n + m).
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
if str1 + str2 != str2 + str1:
return ""
return str1[:math.gcd(len(str1), len(str2))]
assert Solution().gcdOfStrings("ABCABC", "ABC") == "ABC"
assert Solution().gcdOfStrings("ABABAB", "ABAB") == "AB"
assert Solution().gcdOfStrings("LEET", "CODE") == ""
assert Solution().gcdOfStrings("ABABABAB", "ABAB") == "ABAB"
assert Solution().gcdOfStrings("AAAA", "AA") == "AA"
class Solution {
public String gcdOfStrings(String str1, String str2) {
if (!(str1 + str2).equals(str2 + str1)) return "";
return str1.substring(0, gcd(str1.length(), str2.length()));
}
private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
}
func gcdOfStrings(str1 string, str2 string) string {
if str1+str2 != str2+str1 { // no common repeating unit
return ""
}
a, b := len(str1), len(str2)
for b != 0 {
a, b = b, a%b
}
return str1[:a]
}