class Solution {
public String gcdOfStrings(String str1, String str2) {
int length1 = str1.length();
int length2 = str2.length();
int min = length1 < length2 ? length1 : length2;
String result = "";
for (int i = 1; i <= min; i++) {
// 截取两个字符串
String s1 = str1.substring(0, i);
String s2 = str2.substring(0, i);
// 得到替换后的字符串
String r1 = str1.replace(s1, "");
String r2 = str2.replace(s2, "");
// 判断替换后的字符串是否为空,且截取的字符串相同
if (r1.equals("") && r2.equals("") && s1.equals(s2)) {
result = s1;
}
}
return result;
}
}
LeetCode:[1071] 字符串的最大公因子
最新推荐文章于 2024-09-07 19:07:25 发布