3.12 string GCD

topic

For strings S and T, only S = T + ... + time T (T connected to itself one or more times), we identified "T S can be divisible."

Returns the longest string X, X can meet the requirements, and X can be divisible divisible str1 str2.

Example 1

输入:str1 = "ABCABC", str2 = "ABC"
输出:"ABC"

Example 2

输入:str1 = "ABABAB", str2 = "ABAB"
输出:"AB"

Example 3

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

Thinking

  • Euclidean algorithm with the idea of ​​number theory. And a character string str1 str2, assuming str1 is longer.
  • With str2 kept to match str1, until it can not match. The remaining str1 as str2, as the original str2 str1. Until one a full match at this time is to do the Grand Duke str2 factor.
    Here Insert Picture Description

Code

class Solution {
public:
    string gcdOfStrings(string str1, string str2) {
        if ( !str1.size() || !str2.size() )
            return "";
        
        if ( str1.size() < str2.size() )
            swap( str1, str2);

        while ( str2.size() ) {
            int size2 = str2.size();
            int start = 0;

            while ( start + size2 <= str1.size() ) {
                if ( str1.substr( start, size2) != str2 )
                    return "";

                start += size2;
            }

            str1 = str1.substr( start );
            swap( str1, str2 );
        }

        return str1;
    }

    void swap( string& str1, string& str2 ) {
        string temp = str1;
        str1 = str2;
        str2 = temp;

        return;
    }
};
He published 183 original articles · won praise 43 · views 60000 +

Guess you like

Origin blog.csdn.net/m0_37822685/article/details/104827594
gcd