【Leetcode_总结】 1071. 字符串的最大公因子 - python

Q:

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

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

 

示例 1:

输入:str1 = "ABCABC", str2 = "ABC"
输出:"ABC"

示例 2:

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

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

思路:暴力求解

代码:

class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        if len(str1) > len(str2):
            s1, s2 = str1, str2
        else:
            s2, s1 = str1, str2
        if s1.replace(s2,'') == '':
            return s2
        i = len(s2)
        while i <= len(s2) and i != 0:
            temp1 = s1
            temp2 = s2
            if temp1.replace(s2[:i],'') == '' and temp2.replace(s2[:i],'') == '':
                return s2[:i]
            else:
                i-=1
        return ''

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值