1. 题目

2. 解题思路
满足题目要求的子串长度为两个字符串长度的最大公因数gcd
计算最大公因数gcd,若两个字符串以gcd为周期,且前gcd字符相同
则前gcd字符为题解
PS: 如果str1 + str2 == str2 + str1则一定有公因子
辗转相除法:
两个数的最大公约数等于它们中较小的数和两数之差的最大公约数。
3. 代码
class Solution {
public:
string gcdOfStrings(string str1, string str2) {
int gcd = 0;
int a = str1.size();
int b = str2.size();
// 辗转相除法
while(a != b){
// cout<<a<<" "<<b<<endl;
if(a < b){
b = b - a;
}else if(a > b){
b = a - b;
a = - (b - a);
}
}
// 最大公因数
gcd = a;
// cout<<gcd<<endl;
// 校验
// for(int i = 0; i < gcd; i++){
// if(str1[i] != str2[i]){
// return "";
// }
// }
// for(int i = gcd; i < str1.size(); i++){
// if(str1[i] != str1[i - a]){
// return "";
// }
// }
// for(int i = gcd; i < str2.size(); i++){
// if(str2[i] != str2[i - a]){
// return "";
// }
// }
if(str1 + str2 != str2 + str1){
return "";
}
return str1.substr(0, gcd);
}
};

本文介绍了一种求解两个字符串最大公因数的算法,通过计算字符串长度的最大公约数并验证是否符合周期条件,实现了字符串子串的有效查找。特别地,文章提供了详细的解题思路及C++代码实现。
1126

被折叠的 条评论
为什么被折叠?



