1071. Greatest Common Divisor of Strings (GCD string)
link
https://leetcode-cn.com/problems/greatest-common-divisor-of-strings
topic
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: ""
Tip:
. 1 <= str1.length <= 1000
. 1 <= str2.length <= 1000
str1 [I] and str2 [i] uppercase letters
Thinking
Be it math, if str1 + str2 and str2 + str1 same, the divisor would like to request the presence of it, and the length already know, is the common divisor of string length, only the output of a long string interception that section can be.
Code
public int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
public String gcdOfStrings(String str1, String str2) {
if ((str1 + str2).equals(str2 + str1)) {
return str1.substring(0, gcd(str1.length(), str2.length()));
} else {
return "";
}
}