-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathleetcode1071-greatst-common-divisor-of-strings.cpp
61 lines (53 loc) · 1.45 KB
/
leetcode1071-greatst-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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* leetcode1071-greatst-common-divisor-of-strings.cpp
*
* @author Wang Guibao (wang_guibao@163.com)
* @date 2023/10/09 15:59
* @brief https://leetcode.com/problems/greatest-common-divisor-of-strings
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
string gcdOfStrings(string str1, string str2) {
std::string gcd;
while (!str1.empty() && ! str2.empty()) {
if (str1.length() == str2.length()) {
if (str1 == str2) {
gcd = str1;
}
break;
} else if (str1.length() > str2.length()) {
if (str1.substr(0, str2.length()) != str2) {
break;
}
str1 = str1.substr(str2.length());
} else {
if (str2.substr(0, str1.length()) != str1) {
break;
}
str2 = str2.substr(str1.length());
}
}
return gcd;
}
};
int main() {
while (1) {
std::string str1;
std::string str2;
std::cout << "Input str1: ";
if (!std::getline(std::cin, str1)) {
return 0;
}
std::cout << "Input str2: ";
if (!std::getline(std::cin, str2)) {
return 0;
}
Solution solution;
auto ret = solution.gcdOfStrings(str1, str2);
std::cout << ret << std::endl;
}
return 0;
}