Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit00125b7

Browse files
committed
Create 1071-greatest-common-divisor-of-strings.java
1 parentd642910 commit00125b7

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
classSolution {
2+
3+
// Helper function to calculate gcd using Euclidean algorithm
4+
publicintgcd(inta,intb){
5+
if(b ==0){
6+
returna;
7+
}
8+
returngcd(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+
publicStringgcdOfStrings(Stringstr1,Stringstr2) {
19+
if((str1 +str2).equals(str2 +str1)){
20+
intlen1 =str1.length();
21+
intlen2 =str2.length();
22+
intgcd =gcd(len1,len2);
23+
returnstr1.substring(0,gcd);
24+
}
25+
return"";
26+
}
27+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp