python【力扣LeetCode算法题库】1071. 字符串的最大公因子
2020-03-23 18:35
676 查看
- 字符串的最大公因子
对于字符串 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] 为大写英文字母
思路:
求出字符串长度上的最大公因子,根据长度提取字符串前缀,判断前缀是否相等以及每个字符串是否由前缀组成。
class Solution(object): def gcdOfStrings(self, str1, str2): if len(str1) < len(str2): str1, str2 = str2, str1#将短的字符串赋给str2 len_str1 = m = len(str1) len_str2 = n = len(str2) res = '' while n > 0: m, n = n, m%n#辗转相除法求最大公因子 gcd = m rep1, rep2 = str1[:gcd], str2[:gcd] #判断最大公因子对应的前缀是否相等,以及是否能构成字符串str1和str2 if rep1 == rep2 and str1 == rep1*(len_str1//gcd ) and str2 == len_str2//gcd*rep2: return rep1 return res
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- python【力扣LeetCode算法题库】面试题 01.06-字符串压缩
- python【力扣LeetCode算法题库】836- 矩形重叠
- python【力扣LeetCode算法题库】1160-拼写单词
- python【力扣LeetCode算法题库】300 最长上升子序列(动态规划)
- python【力扣LeetCode算法题库】169 多数元素
- python【力扣LeetCode算法题库】876- 链表的中间结点
- python【力扣LeetCode算法题库】945- 使数组唯一的最小增量
- python【力扣LeetCode算法题库】365- 水壶问题(裴蜀等式)
- leetcode-1071 字符串的最大公因子 Python
- python【力扣LeetCode算法题库】面试题40- 最小的k个数
- python【力扣LeetCode算法题库】409-最长回文串(数学 计数器)
- leetcode 1071. 字符串的最大公因子
- LeetCode初级算法的Python实现--字符串
- leetcode 1071. 字符串的最大公因子
- Leetcode 1071. 字符串的最大公因子
- 力扣(leetcode 8)字符串转换整数 (atoi) python
- LeetCode探索模块初级算法字符串章节python3代码实现
- 每日一道LeetCode:1071. 字符串的最大公因子
- LeetCode探索模块初级算法链表章节python3代码实现
- 【leetcode】字符串的常见算法问题总结(LIS、LCS、LCP、LPS、ED、KMP)