- Greatest Common Divisor of Strings
For two strings s
and t
, we say "t
divides s
" if and only if s = t + ... + t
(i.e., t
is concatenated with itself one or more times).
Given two strings str1
and str2
, return the largest string x
such that x
divides both str1
and str2
.
// runtime 93.75% memory 95.83%
var gcdOfStrings = function(str1, str2) {
function gcd(str1, str2) {
if (str2.length == 0) {
return str1
}
if (str1.indexOf(str2) == -1) {
return ""
}
while (str1.startsWith(str2)) {
str1 = str1.substr(str2.length)
}
return gcd(str2, str1)
}
return str1.length > str2.length ? gcd(str1, str2) : gcd(str2, str1)
}