算法练习-LeetCode1071. Greatest Common Divisor of Strings

该问题涉及字符串处理,要求找到两个给定字符串的最大公约串。方法包括检查字符串拼接的对称性以及使用欧几里得算法计算长度的最大公约数(GCD)。解题关键在于确保字符串能通过自身重复形成对方。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:LeetCode - The World's Leading Online Programming Learning Platform

Description: 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: ""

 这道题一开没有想出来就直接放弃看别人的做法,看完之后才发现难怪自己想不粗来。真的不看别人的思路,直接看代码都看不懂😭。

参考的之后写的解题代码如下:

class Solution {
    public String gcdOfStrings(String str1, String str2) {

        if(!(str1+str2).equals(str2+str1)){
            return "";
        }
        int gcd = getGcd(str1.length(),str2.length());

        return str1.substring(0,gcd);
        
    }
    
    public int getGcd(int a , int b){
        if(b == 0) return a;
        return getGcd(b,a%b);
    }

}

思路:

(1)Corner Case:两个String 要有 Greatest Common Divisor(GCD)的话,左边右边拼接起来都应该是完全一样的,不能存在不同的情况:

"ABCEABCEABCE" + "ABCE" = "ABCEABCEABCEABCE"

"ABCE" + "ABCEABCEABCE" = "ABCEABCEABCEABCE"

如果存在不同的情况,就不存在最大GCD:

"ABAB" + "BB" = "ABABBB"

"BB" + "ABAB" = "BBABAB"

(2)存在GCD的情况下,如下其GCD的长度是两个String长度的最大公因子:

"ABCEABCEABCE" + "ABCE" = "ABCEABCEABCEABCE"

               12                        4                 ->      4 (最大公因子 = GCD长度)

"ABCE" + "ABCEABCEABCE" = "ABCEABCEABCEABCE"

通过递归找到GCD长度:

 public int getGcd(int a , int b){
        if(b == 0) return a;
        return getGcd(b,a%b);
    }

然后通过找到的GCD长度substring其中任意一个string就能找到GCD。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值