Skip to content

Commit 00125b7

Browse files
committed
Create 1071-greatest-common-divisor-of-strings.java
1 parent d642910 commit 00125b7

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Diff for: java/1071-greatest-common-divisor-of-strings.java

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
3+
// Helper function to calculate gcd using Euclidean algorithm
4+
public int gcd(int a, int b){
5+
if(b == 0){
6+
return a;
7+
}
8+
return gcd(b, a%b);
9+
}
10+
11+
/*
12+
Approach: If the string have a GCD, then str1 will be of the form m*GCD and str2 will be of the form n*GCD.
13+
So, str1 + str2 = m*GCD + n*GCD = (m+n)*GCD, hence str1 + str2 should be equal to str2 + str1.
14+
If the above condition is satisfied, then we can find the GCD of the lengths of the strings and return the substring of str1 of length GCD.
15+
Else, return empty string.
16+
*/
17+
18+
public String gcdOfStrings(String str1, String str2) {
19+
if((str1 + str2).equals(str2 + str1)){
20+
int len1 = str1.length();
21+
int len2 = str2.length();
22+
int gcd = gcd(len1, len2);
23+
return str1.substring(0, gcd);
24+
}
25+
return "";
26+
}
27+
}

0 commit comments

Comments
 (0)