Greatest common factor C ++ string 1071. Two Hundred Day question

1071. GCD string

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:

Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"

Example 2:

Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"

Example 3:

Input: str1 = "LEET", str2 = "CODE"
Output: ""

prompt:

. 1 <= str1.length <= 1000
. 1 <= str2.length <= 1000
str1 [I] and str2 [i] uppercase letters

Thinking

str1 + str2 == str2 + str1 certainly present common factors. And the string must be the greatest common factor of the length of the largest common factor.

My answer

Here Insert Picture Description

class Solution {
public:
    string gcdOfStrings(string str1, string str2) {
        int lenStr1 = str1.length();
        int lenStr2 = str2.length();
        if (str1 + str2 == str2 + str1) {
            return str1.substr(0,gcd(lenStr1, lenStr2));
        }
        else return "";
    }
};

inline int gcd(int a, int b) {
    if (b) while ((a %= b) && (b %= a));
    return a + b;
}
Published 38 original articles · won praise 0 · Views 1030

Guess you like

Origin blog.csdn.net/Cyan1956/article/details/104813659