字符串的最大公因子

在这里插入图片描述

题目要求的是求最大公因数,想当然地写成了最小公因数,实在是太菜了。
可以使用辗转相除法求最大公因数。
有种解题思路是这样的,就是求字符串A.length() 和字符串B.length()的最大公约数,例如ABCABC,ABC 。长度分别是6 和 3,因此两个字符串的最大公约数就是3,所以最大公约数就是str1.subString(0,3);再如 ABABAB 和 ABAB,长度分别为 6,4,所以最大公约数为2,所以最大公约数就是str1.substring(0,2)。

 public int gcd(int a,int b){
        while(b!=0){
            int temp = b;
            b = a%b;
            a = temp;
        }
        return a;
    }
    public String gcdOfStrings(String str1, String str2) {
        // 假设str1是N个x,str2是M个x,那么str1+str2肯定是等于str2+str1的。
        if (!(str1 + str2).equals(str2 + str1)) {
            return "";
        }
        // 辗转相除法求gcd。
        return str1.substring(0, gcd(str1.length(), str2.length()));
    }

来源:https://leetcode-cn.com/problems/greatest-common-divisor-of-strings/solution/java-hen-jian-ji-yi-yan-jiu-neng-kan-ming-bai-by-s/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值