1071. 字符串的最大公因子
对于字符串 S 和 T,只有在 S = T + … + T(T 与自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。
返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。
示例 1:
输入:str1 = “ABCABC”, str2 = “ABC”
输出:“ABC”
示例 2:
输入:str1 = “ABABAB”, str2 = “ABAB”
输出:“AB”
示例 3:
输入:str1 = “LEET”, str2 = “CODE”
输出:""
提示:
1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1[i] 和 str2[i] 为大写英文字母
思路
str1+str2==str2+str1则必存在公因子。而字符串的最大公因子也一定是长度上最大公因子。
我的解答
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;
}