[String] C014_ string GCD (greatest common divisor)

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 a . a p p e n d ( b ) = = b . a p p e n d ( a ) a.append(b) == b.append(a)

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: O ( l O g ( n ) ) O(log(n))
  • Space complexity: O ( 1 ) O (1) ,
Published 495 original articles · won praise 105 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_43539599/article/details/104812846