-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGreatest Common Divisor of Strings.cpp
More file actions
44 lines (39 loc) · 1.03 KB
/
Greatest Common Divisor of Strings.cpp
File metadata and controls
44 lines (39 loc) · 1.03 KB
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
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
string gcdOfStrings(string str1, string str2)
{
int str1Lenth = str1.size();
int str2Lenth = str2.size();
int minLenth = min(str1Lenth, str2Lenth);
string res="";
for(int i= minLenth; i>=1;i--)
{
if((str1Lenth % i == 0) && (str2Lenth % i == 0))
{
int l1r = str1Lenth / i;
int l2r = str2Lenth / i;
string padstr = str1.substr(0, i);
string rebuildStr1 = genRpstr(l1r, padstr);
string rebuildStr2 = genRpstr(l2r, padstr);
if(rebuildStr1 == str1 && rebuildStr2 == str2)
{
res = padstr;
break;
}
}
}
return res;
}
string genRpstr(int times, string subStr)
{
string res="";
while(times--)
{
res += subStr;
}
return res;
}
};