Skip to content

Commit a641ba2

Browse files
authored
Create greatest-common-divisor-of-strings.cpp
1 parent 972b28d commit a641ba2

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Time: O(m + n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
string gcdOfStrings(string str1, string str2) {
7+
if (str1.empty() || str2.empty()) {
8+
return "";
9+
}
10+
int c = gcd(str1.length(), str2.length());
11+
const auto& result = str1.substr(0, c);
12+
return check(str1, result) && check(str2, result) ? result : "";
13+
}
14+
15+
private:
16+
bool check(const string& s, const string& common) {
17+
int i = 0;
18+
for (const auto& c : s) {
19+
if (c != common[i]) {
20+
return false;
21+
}
22+
i = (i + 1) % common.length();
23+
}
24+
return true;
25+
}
26+
27+
int gcd(int a, int b) {
28+
while (b != 0) {
29+
int tmp = b;
30+
b = a % b;
31+
a = tmp;
32+
}
33+
return a;
34+
}
35+
};

0 commit comments

Comments
 (0)