1071. 字符串的最大公因子
为保证权益,题目请参考 1071. 字符串的最大公因子(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
class Solution
{
public:
string gcdOfStrings(string str1, string str2)
{
string ans = "";
int str1_len = str1.length();
int str2_len = str2.length();
for (int j = 1; j <= min(str1_len, str2_len); ++j)
{
if (str1_len % j == 0 && str2_len % j == 0)
{
string tmp = str1.substr(0, j);
bool flag1 = true;
bool flag2 = true;
for (int i = 0; i < str1_len / j; ++i)
{
string str1_tmp = str1.substr(i * j, j);
if (str1_tmp != tmp)
{
flag1 = false;
break;
}
}
for (int i = 0; i < str2_len / j; ++i)
{
string str2_tmp = str2.substr(i * j, j);
if (str2_tmp != tmp)
{
flag2 = false;
break;
}
}
if (flag1 && flag2)
{
ans = tmp;
}
}
}
return ans;
}
};
int main()
{
Solution so;
cout << so.gcdOfStrings("ABABAB", "ABAB");
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56