LeetCode] [1071. Greatest Common Divisor of the greatest common divisor Strings string (Easy) (JAVA)
Topic Address: https://leetcode.com/problems/greatest-common-divisor-of-strings/
Subject description:
For strings S and T, we say “T divides S” if and only if S = T + … + T (T concatenated with itself 1 or more times)
Return the largest string X such that X divides str1 and X divides 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: ""
Note:
1. 1 <= str1.length <= 1000
2. 1 <= str2.length <= 1000
3. str1[i] and str2[i] are English uppercase letters.
Subject to the effect
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.
Problem-solving approach
Common way is to traverse find common factors
class Solution {
public String gcdOfStrings(String str1, String str2) {
if (str1.length() == 0 || str2.length() == 0) return "";
int start = 0;
for (; start < str1.length() && start < str2.length(); start++) {
if (str1.charAt(start) != str2.charAt(start)) break;
}
if (start <= 0) return "";
if (str1.length() < str2.length()) {
String temp = str1;
str1 = str2;
str2 = temp;
}
for (int i = start - 1; i >= 0; i--) {
if (str1.length() % (i + 1) != 0 || str2.length() % (i + 1) != 0 || !str2.equals(str1.substring(0, str2.length()))) continue;
String temp = str1.substring(0, i + 1);
int j = 1;
for (; (j + 1) * (i + 1) <= str1.length() || (j + 1) * (i + 1) <= str2.length(); j++) {
if ((j + 1) * (i + 1) <= str1.length()) {
if (!temp.equals(str1.substring(j * (i + 1), (j + 1) * (i + 1)))) break;
}
if ((j + 1) * (i + 1) <= str2.length()) {
if (!temp.equals(str2.substring(j * (i + 1), (j + 1) * (i + 1)))) break;
}
}
if ((j + 1) * (i + 1) > str1.length() && (j + 1) * (i + 1) > str2.length()) return temp;
}
return "";
}
}
When execution: 4 ms, beat the 28.07% of all users to submit in Java
memory consumption: 39 MB, beat the 8.80% of all users to submit in Java
A look at the rankings, we know that this approach is too time-consuming, looked behind the great God of practice
class Solution {
public String gcdOfStrings(String str1, String str2) {
if (!(str1 + str2).equals(str2 + str1)) return "";
return str1.substring(0, gcd(str1.length(), str2.length()));
}
public int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
When execution: 1 ms, beat the 93.63% of all users to submit in Java
memory consumption: 38.4 MB, defeated 10.40% of all users to submit in Java