-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGCDString.java
More file actions
40 lines (34 loc) · 1.17 KB
/
GCDString.java
File metadata and controls
40 lines (34 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class GCDString {
public static void main(String[] args) {
System.out.println(new GCDString().gcdOfStrings("ABCABC", "ABC"));
System.out.println(new GCDString().gcdOfStrings("LEET", "CODE"));
System.out.println(new GCDString().gcdOfStrings("ABABAB", "ABAB"));
System.out.println(new GCDString().gcdOfStrings("ABABCCABAB", "ABAB"));
}
private static int GCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public String gcdOfStrings(String str1, String str2) {
int n = str1.length();
int m = str2.length();
// put the longer string as the first argument
if (n < m)
return gcdOfStrings(str2, str1);
int k = 0;
while (k+m <= n) {
if (!str1.startsWith(str2, k))
return "";
k = k + m;
}
if (!str1.endsWith(str2))
return "";
// find the GCD of the string length
int gcd = GCD(n, m);
return str2.substring(0, gcd);
}
}