Skip to content

Commit 1526df3

Browse files
committed
1071-greatest-common-divisor-of-strings
1 parent e62fc00 commit 1526df3

2 files changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package main
2+
3+
import "strings"
4+
5+
func main() {
6+
7+
}
8+
9+
func gcdOfStrings(str1 string, str2 string) string {
10+
len1, len2 := len(str1), len(str2)
11+
var isDivisor func(l int) bool
12+
13+
isDivisor = func(l int) bool {
14+
if len1%l != 0 || len2%l != 0 {
15+
return false
16+
}
17+
18+
f1, f2 := len1/l, len2/l
19+
20+
return strings.Repeat(str1[:l], f1) == str1 && strings.Repeat(str1[:l], f2) == str2
21+
}
22+
23+
for l := min(len1,len2); l > 0; l-- {
24+
if isDivisor(l) {
25+
return str1[:l]
26+
}
27+
}
28+
29+
return ""
30+
}
31+
32+
func min( a,b int) int {
33+
if a < b {
34+
return a
35+
}
36+
return b
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @param {string} str1
3+
* @param {string} str2
4+
* @return {string}
5+
*/
6+
var gcdOfStrings = function (str1, str2) {
7+
let [len1, len2] = [str1.length, str2.length];
8+
9+
function isDivisor(l) {
10+
if (len1 % l || len2 % l) {
11+
return false;
12+
}
13+
14+
let [f1, f2] = [Math.floor(len1 / l), Math.floor(len2 / l)];
15+
16+
return (
17+
str1.slice(0, l).repeat(f1) == str1 && str1.slice(0, l).repeat(f2) == str2
18+
);
19+
}
20+
21+
for (let l = Math.min(len1, len2); l > 0; l--) {
22+
if (isDivisor(l)) {
23+
return str1.slice(0, l);
24+
}
25+
}
26+
27+
return "";
28+
};

0 commit comments

Comments
 (0)