Open songyy5517 opened 6 months ago
Approach: Repeating String Property & GCD
str1 + str2 == str2 + str1
Complexity Analysis
str1
and str2
respectively, the concatenation of these two strings costs $O(M+N)$ , and the time complexity of Euclidean Algorithm is $O(log_2N)$ . Therefore, the entire complexity is $O(M+N+logN) = O(M+N)$ .class Solution {
public String gcdOfStrings(String str1, String str2) {
// Intuition: 判断循环串 & 求循环串。
// 1. Exception Handling
if (str1 == null || str2 == null || !(str1 + str2).equals(str2 + str1))
return "";
// 2. Compute GCD
return str1.substring(0, gcd(str1.length(), str2.length()));
}
// 辗转相除法:求最大公因数GCD: greatest common divisor
int gcd(int x, int y){
int rem = x % y;
while (rem != 0){
x = y;
y = rem;
rem = x % y;
}
return y;
}
}
2024/5/6
For two strings
s
andt
, we say "t
dividess
" if and only ifs = t + t + t + ... + t + t
(i.e.,t
is concatenated with itself one or more times).Given two strings
str1
andstr2
, return the largest stringx
such thatx
divides bothstr1
andstr2
.Example 1:
Example 2:
Example 3:
Intuition This problem mainly examines the properties of String. The whole task can be broken down into two sections: 1. Determine whether two strings contain common divisor; 2. Find their greatest common divisor. For the first one, we can check whether
str1 + str2 == str2 + str1
. To obtain their GCD, we can first calculate the GCD of their length, then the result is the substring(0, GCD).