-
Notifications
You must be signed in to change notification settings - Fork 1
/
GreatestCommonDivisorOfStrings.java
33 lines (28 loc) · 1.09 KB
/
GreatestCommonDivisorOfStrings.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.smlnskgmail.jaman.leetcodejava.easy;
// https://leetcode.com/problems/greatest-common-divisor-of-strings/
public class GreatestCommonDivisorOfStrings {
private final String first;
private final String second;
public GreatestCommonDivisorOfStrings(String first, String second) {
this.first = first;
this.second = second;
}
public String solution() {
int firstLength = first.length();
int secondLength = second.length();
int maxLength = Math.max(firstLength, secondLength);
for (int i = maxLength; i >= 1; i--) {
if (firstLength % i == 0 && secondLength % i == 0) {
String firstSub = first.substring(0, i);
String secondSub = second.substring(0, i);
if (firstSub.equals(secondSub)) {
if ((first.substring(i) + firstSub).equals(first)
&& (second.substring(i) + secondSub).equals(second)) {
return firstSub;
}
}
}
}
return "";
}
}