forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1071-greatest-common-divisor-of-strings.cpp
47 lines (38 loc) · 1.18 KB
/
1071-greatest-common-divisor-of-strings.cpp
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
/**
* Time Complexity: O(n^2)
* Space Complexity: O(1)
*/
class Solution {
public:
string gcdOfStrings(string str1, string str2) {
string shortest, longest;
if(str1.length() < str2.length()){
shortest = str1;
longest = str2;
}
else{
shortest = str2;
longest = str1;
}
string solution = "";
ushort shortest_length = shortest.length();
ushort longest_length = longest.length();
for(ushort i = shortest_length; i > 0; --i)
{
if (longest_length % i != 0 || shortest_length % i != 0) continue;
for(ushort j = 0; j < longest_length; ++j)
{
ushort first_pointer = j % i;
ushort second_pointer = j % shortest_length;
if(shortest[first_pointer] != longest[j] || shortest[second_pointer] != longest[j])
{
solution = "";
break;
}
if(first_pointer == j) solution += longest[j];
}
if(solution != "") return solution;
}
return "";
}
};