当前位置:   article > 正文

LeetCode 1071. Greatest Common Divisor of Strings

LeetCode 1071. Greatest Common Divisor of Strings

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.

Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Input: str1 = "LEET", str2 = "CODE"
Output: ""

Note:

1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1[i] and str2[i] are English uppercase letters.

思路:

根据题意,如果str2是str1的若干个组成,那必然存在str1 + str2 == str2 + str1,反之亦然,即如果str1 + str2 != str2 + str1,那么这两个字符串一定不存在公因式。

又因为找最大公因子,所以可以从最大开始遍历,两个字符串都会是最大公因子的整数个组成,即gcd_str * n1 == str1 and gcd_str * n2 == str2; 其中n1表示多少个公因子组成str1,n2表示多少个公因子组成str2

 

  1. class Solution:
  2.     def gcdOfStrings(self, str1: str, str2: str) -> str:
  3.         if str1 + str2 != str2 + str1:
  4.             return ""
  5.         size1 = len(str1)
  6.         size2 = len(str2)
  7.         for i in range(min(size1, size2), 0, -1):
  8.             if size1 % i == 0 and size2 % i == 0:
  9.                 if str1[:i] * (size1 // i) == str1 and str1[:i] * (size2 // i) == str2:
  10.                     return str1[:i]
  11.         return ""

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/493430
推荐阅读
相关标签
  

闽ICP备14008679号