LeetCode 1071. Greatest Common Divisor of Strings

1071. Greatest Common Divisor of Strings(字符串的最大公因子)

链接

https://leetcode-cn.com/problems/greatest-common-divisor-of-strings

题目

对于字符串 S 和 T,只有在 S = T + ... + T(T 与自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。

返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。

示例 1:

输入:str1 = "ABCABC", str2 = "ABC"
输出:"ABC"
示例 2:

输入:str1 = "ABABAB", str2 = "ABAB"
输出:"AB"
示例 3:

输入:str1 = "LEET", str2 = "CODE"
输出:""
 
提示:

1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1[i] 和 str2[i] 为大写英文字母

思路

算是数学题吧,如果str1+str2和str2+str1相同的话,那就存在想要求的公约数,并且长度就已经知道了,就是字符串长度的公约数,只需要输出长的字符串截取的那部分即可。

代码

  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 "";
    }
  }

猜你喜欢

转载自www.cnblogs.com/blogxjc/p/12468151.html