One, Title Description
对于字符串 S 和 T,只有在 S = T + ... + T(T 与自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。
返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。
输入:str1 = "ABCABC", str2 = "ABC"
输出:"ABC"
Second, the problem solution
Method One: gcd
GCD: If the number of integers x, if x can be divisible both a and b, then x is a, b of the greatest common divisor.
For strings: if x can be a, b simultaneously divisible, then ;
Furthermore, if they have a common factor ab &, s1 then m is an "ab", s2 is the n "ab", is put together m + n th "ab".
Simply return to the last substring or a greatest common divisor of b length.
public String gcdOfStrings(String s1, String s2) {
if (s1 == null || s2 == null) {
return null;
} else if (!(s1 + s2).equals(s2 + s1)) {
return "";
}
return s1.substring(0, gcd(s1.length(), s2.length()));
}
int gcd (int a, int b) {
if (a == 0 || b == 0)
return a == 0 ? b : a;
return gcd(b, a % b);
}
Complexity Analysis
- time complexity: ,
- Space complexity: ,