Greatest Common Divisor of Strings LeetCode solution in Java

1
class Solution {
2
public String gcdOfStrings(String str1, String str2) {
3

4
int length1 = str1.length();
5
int length2 = str2.length();
6
String temp;
7

8
for (int i = gcd(length1, length2); i > 0 && length1 % i == 0 && length2 % i == 0; i--) {
9
if (str1.substring(0, i).equals(str2.substring(0, i))) {
10
if (doesRepeat(str1.substring(0, i), str1, str2)) return str1.substring(0, i);
11
}
12
}
13
return "";
14
}
15

16
public int gcd(int a, int b) {
17
if (b == 0) return a;
18
return gcd(b, a % b);
19
}
20

21
public boolean doesRepeat(String s, String str1, String str2) {
22
int sLength = s.length();
23
boolean bool1 = true, bool2 = true;
24
String temp = str1, temp2;
25

26
while (sLength < temp.length()) {
27
temp2 = temp.substring(sLength, sLength * 2);
28

29
if (s.equals(temp2))
30
;
31
else bool1 = false;
32
temp = temp.substring(sLength, temp.length());
33
}
34
temp = str2;
35
while (sLength < temp.length()) {
36
temp2 = temp.substring(sLength, sLength * 2);
37
if (s.equals(temp2))
38
;
39
else bool2 = false;
40
temp = temp.substring(sLength, temp.length());
41
}
42
return bool1 && bool2;
43
}
44
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0