leetcode 1071. Greatest Common Divisor of Strings(字符串的最大公约数)

For two strings s and t, we say “t divides s” if and only if s = t + … + t (i.e., t is concatenated with itself one or more times).

Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.

Example 1:

Input: str1 = “ABCABC”, str2 = “ABC”
Output: “ABC”

Example 2:

Input: str1 = “ABABAB”, str2 = “ABAB”
Output: “AB”

Example 3:

Input: str1 = “LEET”, str2 = “CODE”
Output: “”

字符串t 能整除字符串 s 表示 s = t + … + t, 即多个t 能拼接成 s.
求s 和 t 的最大公约数字符串。

思路:

这是个求最大公约数(gcd)的问题,
回忆一下求两个数a,b 的最大公约数 gcd(a,b) = (b == 0 ? a : gcd(b, a%b).

如果 s1 和 s2 中都只有一种字母,比如 s1 = AAAA, s2 = AA
那么公约数可以有A, AA, 其实就是gcd(s1.length, s2.length) = gcd(4, 2) = 2
最大公约数的长度是2, 也就是AA

那如果有多个字母呢?其实也是一样的,前提是它们要有公约数,
如何判断是不是有公约数?
如果有,那么s1 和 s2 都可以用公约数拼接而成,s1 和 s2谁在前谁在后都可以整除公约数,且整除的结果是一样的。
即 s1 + s2 == s2 + s1 时它们有公约数.

只要有公约数,就可以用gcd(s1.length, s2.length)来求公约数的长度,然后根据长度取出子字符串即为最大公约数。

    public String gcdOfStrings(String str1, String str2) {
        if(!(str1 + str2).equals(str2 + str1)) return "";
        
        int len = gcd(str1.length(), str2.length());
        return str1.substring(0,len);
    }

    int gcd(int a, int b) {
        return (b == 0 ? a : gcd(b, a % b));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值