leetcode1071: GCD string

Title understood meaning given str1 and str2 two strings, strings divisible requirements X.

Divisible means that str1 and str2 can be represented by multiple X.

The X as a string, a string of size greater than or equal to 1.

str1 = AX
str2 = BX

The purpose is to seek X.

From the above formula, may first be determined whether divisible, can be divisible when, to satisfy: str1 + str2 = str2 + str1

Then, after satisfying be divisible by gcd algorithm, i.e., Euclidean algorithm.

Euclidean: the greatest common divisor of two numbers is equal to the number of two larger / smaller number and the remainder divided by the number two common divisor

A look is to use a recursive approach, divided by the number two until the remainder is 0, then the greatest common divisor of two numbers is equal to the current divisor.

Regardless of the length of str1 and str2, because [the greatest common divisor of two numbers is equal to the number two larger / smaller numbers and two numbers divided by the greatest common divisor of the remainder]

Take the larger / smaller number than the remainder and go just fine.

  int gcd(int a,int b) { return !b? a:gcd(b,a%b); }

    string gcdOfStrings(string str1, string str2) {
           return (str1+str2) == (str2 + str1) ? str1.substr(0, gcd( str1.size(), str2.size()))  : "";
    }
Published 44 original articles · won praise 51 · views 80000 +

Guess you like

Origin blog.csdn.net/Hanghang_/article/details/104906066
gcd