Source: https: //leetcode-cn.com/problems/greatest-common-divisor-of-strings/solution/1071-zi-fu-chuan-de-zui-da-gong-yin-zi-by-wonderfu/
public String gcdOfStrings(String str1, String str2) {
int len1 = str1.length();
int len2 = str2.length();
if (len1 % len2 == 0){
if (isGcd(str1,str2)){
return str2;
} else {
return "";
}
}
if (len2 % len1 == 0){
if (isGcd(str2,str1)){
return str1;
} else {
return "";
}
}
TreeMap<Integer, String> map1 = new TreeMap<>();
int j = len1 - 1;
while (true){
if (len1 % j == 0 && isGcd(str1,str1.substring(0,j))){
map1.put(str1.substring(0,j).length(),str1.substring(0,j));
}
j--;
if (j == 0){
break;
}
}
if (map1.size() == 0){
return "";
}
TreeMap<Integer, String> map2 = new TreeMap<>();
int i = len2 - 1;
while (true){
if (len2 % i == 0 && isGcd(str2,str2.substring(0,i))){
map2.put(str2.substring(0,i).length(),str2.substring(0,i));
}
i--;
if (i == 0){
break;
}
}
if (map2.size() == 0){
return "";
}
ArrayList<String> list = new ArrayList<>();
for (Map.Entry<Integer,String> entry : map2.entrySet()) {
if (map1.containsKey(entry.getKey())){
if (map1.get(entry.getKey()).equals(entry.getValue())){
list.add(entry.getValue());
}
}
}
return list.get(list.size()-1);
}
public boolean isGcd(String str1,String str2){
while (str1.startsWith(str2)){
if (str1.equals(str2)){
return true;
}
str1 = str1.substring(str2.length());
}
return false;
}
//最大公因子算法gcd不会,只会笨办法.
//官方题解
public String gcdOfStrings1(String str1,String str2){
if (!(str1 + str2).equals(str2 + str1)){
return "";
}
return str1.substring(0,gcd(str1.length(),str2.length()));
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b,a % b);
}