File tree 1 file changed +47
-0
lines changed
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Time Complexity: O(n^2)
3
+ * Space Complexity: O(1)
4
+ */
5
+
6
+ class Solution {
7
+ public:
8
+ string gcdOfStrings (string str1, string str2) {
9
+ string shortest, longest;
10
+
11
+ if (str1.length () < str2.length ()){
12
+ shortest = str1;
13
+ longest = str2;
14
+ }
15
+ else {
16
+ shortest = str2;
17
+ longest = str1;
18
+ }
19
+
20
+ string solution = " " ;
21
+ ushort shortest_length = shortest.length ();
22
+ ushort longest_length = longest.length ();
23
+
24
+ for (ushort i = shortest_length; i > 0 ; --i)
25
+ {
26
+ if (longest_length % i != 0 || shortest_length % i != 0 ) continue ;
27
+
28
+ for (ushort j = 0 ; j < longest_length; ++j)
29
+ {
30
+ ushort first_pointer = j % i;
31
+ ushort second_pointer = j % shortest_length;
32
+
33
+ if (shortest[first_pointer] != longest[j] || shortest[second_pointer] != longest[j])
34
+ {
35
+ solution = " " ;
36
+ break ;
37
+ }
38
+
39
+ if (first_pointer == j) solution += longest[j];
40
+ }
41
+
42
+ if (solution != " " ) return solution;
43
+ }
44
+
45
+ return " " ;
46
+ }
47
+ };
You can’t perform that action at this time.
0 commit comments