greatest-common-divisor-of-strings
Title Description
For strings S and T, only S = T + ... + time T (T connected to itself one or more times), we identified "T S can be divisible."
Returns the longest string X, X can meet the requirements, and X can be divisible divisible str1 str2.
Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:
Input: str1 = "LEET", str2 = "CODE"
Output: ""
prompt:
. 1 <= str1.length <= 1000
. 1 <= str2.length <= 1000
str1 [I] and str2 [i] uppercase letters
Code
package pid1071;
public class Solution {
public String gcdOfStrings(String str1,String str2){
// 枚举法
int length1 = str1.length();
int length2 = str2.length();
int maxLength = Math.max(length1, length2);
for(int i=maxLength;i>=1;i--){
if(length1%i==0 && length2%i==0){
String X = str1.substring(0,i);
if(check(str1,X) && check(str2,X)){
return X;
}
}
}
return "";
}
public boolean check(String str,String substr){
int lenx = str.length() / substr.length();
String ans = "";
for(int i=1;i<=lenx;i++){
ans = ans + substr;
}
return str.equals(ans);
}
}