Greatest Common Divisor of Strings

easy string math

Problem

For two strings s and t, we say "t divides s" if and only if s = t + ... + t (t concatenated with itself 1 or more times) Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.

Inputa = "abcabc", b = "abc"
Output"abc"
"abc" repeated 2× = a, repeated 1× = b. gcd(6, 3) = 3.

from math import gcd
def gcd_of_strings(a, b):
    if a + b != b + a:
        return ""
    return a[: gcd(len(a), len(b))]
function gcdOfStrings(a, b) {
  if (a + b !== b + a) return "";
  const gcd = (x, y) => y === 0 ? x : gcd(y, x % y);
  return a.slice(0, gcd(a.length, b.length));
}
class Solution {
    public String gcdOfStrings(String a, String b) {
        if (!(a + b).equals(b + a)) return "";
        int x = a.length(), y = b.length();
        while (y != 0) { int r = x % y; x = y; y = r; }
        return a.substring(0, x);
    }
}
string gcdOfStrings(string a, string b) {
    if (a + b != b + a) return "";
    int x = a.size(), y = b.size();
    while (y) { int r = x % y; x = y; y = r; }
    return a.substr(0, x);
}
Time: O(|a| + |b|) Space: O(|a| + |b|)