[leetcode] 1071. 字符串的最大公因子

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

给定两个字符串 str1 和 str2 。返回 最长字符串 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, str2.length <= 1000
  • str1 和 str2 由大写英文字母组成

Python实现

从最大字串一个一个的匹配得到最终的结果。

复制代码
class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        m = len(str1)
        n = len(str2)
        for i in range(min(len(str1),len(str2)),0,-1):
            if m%i==0 and n%i==0:
                if str1[:i]*(m//i)==str1 and str1[:i]*(n//i)==str2:
                    return str1[:i]
        return ''
相关推荐
曦云沐12 分钟前
【避坑指南】Ubuntu更新报错“Repository is not signed”的快速修复
linux·ubuntu·docker
_不会dp不改名_1 小时前
leetcode_3010 将数组分成最小总代价的子数组 I
算法·leetcode·职场和发展
带土11 小时前
10. .out文件
linux
Exquisite.1 小时前
企业高性能web服务器(4)
运维·服务器·前端·网络·mysql
STCNXPARM1 小时前
Linux camera之V4L2子系统详解
android·linux·camera·v4l2架构
yueyuexiaokeai12 小时前
linux kernel常用函数整理
linux·c语言
郝亚军3 小时前
ubuntu-18.04.6-desktop-amd64安装步骤
linux·运维·ubuntu
Konwledging4 小时前
kernel-devel_kernel-headers_libmodules
linux
Web极客码4 小时前
CentOS 7.x如何快速升级到CentOS 7.9
linux·运维·centos
一位赵4 小时前
小练2 选择题
linux·运维·windows