// 又是自己的暴力..
class Solution {
public String gcdOfStrings(String str1, String str2) {
if(str1 == null || str2 == null) {
return "";
}
String s1, s2;
if (str1.length() < str2.length()) {
s1 = str1;
s2 = str2;
} else {
s1 = str2;
s2 = str1;
}
// 1.短的本身就是T
if (isOk(s1, s2)) {
return s1.toString();
}
int n = 2;
while (n < s1.length()) {
if (s1.length() % n != 0) {
n++;
continue;
}
String curr = s1.substring(0, s1.length() / n);
if (isOk(curr, s1) && isOk(curr, s2)) {
return curr;
}
n++;
}
return "";
}
// bool s1能除尽s2 (s1比s2短)
boolean isOk(String s1, String s2) {
if (s2.length() % s1.length() != 0) {
return false;
}
int n = s2.length() / s1.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(s1);
}
if (sb.toString().equals(s2)) {
return true;
}
return false;
}
}
大佬的数学方法: 正反相加结果相等时,长度就是最大公约数
class Solution {
public String gcdOfStrings(String str1, String str2) {
String s1 = str1 + str2;
String s2 = str2 + str1;
if (!s1.equals(s2)) {
return "";
}
return str1.substring(0, gcd2(str1.length(), str2.length()));
}
// 辗转相除
int gcd(int a, int b) {
if (b == 0 || a == 0) {
return 0;
}
int temp;
while (a % b != 0) {
temp = a % b;
a = b;
b = temp;
}
return b;
}
// 递归
int gcd2(int a, int b) {
if (b == 0) {
return a;
}
return gcd2(b, a % b);
}
}