Skip to content

Commit da5a72f

Browse files
authored
Create 1071-greatest-common-divisor-of-strings.js
1 parent b893da6 commit da5a72f

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {string} str1
3+
* @param {string} str2
4+
* @return {string}
5+
*/
6+
const gcdOfStrings = function(str1, str2) {
7+
let res = "";
8+
9+
if (str1[0] !== str2[0]) return res;
10+
if (str1[str1.length - 1] !== str2[str2.length - 1]) return res;
11+
let s = str1[0];
12+
let e = str1[str1.length - 1];
13+
14+
let loopStr = str1.length > str2.length ? str2 : str1;
15+
for (let i = 1, len = loopStr.length; i < len; i++) {
16+
if (loopStr[i] !== e) continue;
17+
let tmp = loopStr.slice(0, i + 1);
18+
let ok1 = false;
19+
let ok2 = false;
20+
let t1 = "";
21+
let t2 = "";
22+
while (t1.length < str1.length) {
23+
t1 += tmp;
24+
if (t1 === str1) {
25+
ok1 = true;
26+
break;
27+
}
28+
}
29+
while (t2.length < str2.length) {
30+
t2 += tmp;
31+
if (t2 === str2) {
32+
ok2 = true;
33+
break;
34+
}
35+
}
36+
37+
if (ok1 && ok2 && tmp.length > res.length) res = tmp;
38+
}
39+
40+
return res;
41+
};

0 commit comments

Comments
 (0)