每日一题:字符串的最大公因子

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

输入:str1 = “ABCABC”, str2 = “ABC”
输出:“ABC”

输入:str1 = “ABABAB”, str2 = “ABAB”
输出:“AB”

输入:str1 = “LEET”, str2 = “CODE”
输出:""

法1:字符串1和字符串2的公共子字符串的长度一定即是字符串1长度的约数,又是字符串2长度的约数,即它是两个长度的公约数。又因为,两个数的公约数一定是它们最大公约数的约数。所以如果存在这样的子字符串,它的长度一定是原来两个字符串长度的最大公约数。所以继续判断长度为最大公约数的子字符串即可。因此直接从字符串1的开始截取这个长度的字符串,判断它拼接多次后是否可以组成字符串1和字符串2就可以得到结果。

class Solution {
public:
    //检查字符串t拼接多次后能否组成字符串s;
    bool check(string t, string s){
        int lenx = (int)s.length() / (int)t.length();
        string ans = "";
        for (int i = 0; i < lenx; i++){
            ans = ans + t;
        }
        return ans == s;
    }

    int gcd(int a, int b){
        if (a < b){
            int temp = a;
            a = b;
            b = temp;
        }
        if (a % b == 0){
            return b;
        }
        else return gcd(b, a % b);
    }

    string gcdOfStrings(string str1, string str2) {
        int len1 = (int)str1.length(), len2 = (int)str2.length();
        int gcdLength = gcd(len1, len2);
        string commonString = str1.substr(0, gcdLength);
        if (check(commonString, str1) && check(commonString, str2)){
            return commonString;
        }
        return "";    
    }
};

法2:如果str1+str2 == str2 + str1,则说明存在公共子字符串,此时直接截取最大公因数长度的子字符串即可。

class Solution {
public:
    int gcd(int a, int b){
        if (a < b){
            swap(a, b);
        }
        if (a % b == 0){
            return b;
        }
        else return gcd(b, a % b);
    }

    string gcdOfStrings(string str1, string str2) {
        int gcdLen = gcd(str1.length(), str2.length());
        if (str1 + str2 != str2 + str1) return "";
        return str1.substr(0,gcdLen);
    }
};
发布了76 篇原创文章 · 获赞 10 · 访问量 8267

猜你喜欢

转载自blog.csdn.net/weixin_38742280/article/details/104814858