-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode1071.java
More file actions
66 lines (60 loc) · 1.86 KB
/
LeetCode1071.java
File metadata and controls
66 lines (60 loc) · 1.86 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public class LeetCode1071 {
public static void main(String[] args) {
// 输入:str1 = "ABCABC", str2 = "ABC"
// 输出:"ABC"
System.out.println(new Solution1071().gcdOfStrings("ABCABC", "ABC"));
// 输入:str1 = "ABABAB", str2 = "ABAB"
// 输出:"AB"
System.out.println(new Solution1071().gcdOfStrings("ABABAB", "ABAB"));
// 输入:str1 = "LEET", str2 = "CODE"
// 输出:""
System.out.println(new Solution1071().gcdOfStrings("LEET", "CODE"));
}
}
class Solution1071 {
public String gcdOfStrings(String str1, String str2) {
int gcd = getGCD(str1.length(), str2.length());
char[] s1 = str1.toCharArray();
char[] s2 = str2.toCharArray();
for (int len = gcd; len > 0; len--) {
if (str1.length() % len != 0 || str2.length() % len != 0) {
continue;
}
if (check(s1, s2, len)) {
return str1.substring(0, len);
}
}
return "";
}
public int getGCD(int len1, int len2) {
int temp;
while (true) {
len1 = len1 >= len2 ? len1 : len2;
len2 = len1 < len2 ? len1 : len2;
if (len1 % len2 == 0) {
return len2;
}
temp = len1;
len1 = len2;
len2 = temp % len2;
}
}
public boolean check(char[] s1, char[] s2, int len) {
for (int i = 0; i < len; i++) {
if (s1[i] != s2[i]) {
return false;
}
}
for (int i = len; i < s1.length; i++) {
if (s1[i] != s1[i % len]) {
return false;
}
}
for (int i = len; i < s2.length; i++) {
if (s2[i] != s2[i % len]) {
return false;
}
}
return true;
}
}