Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit8fa1f27

Browse files
committed
Create 1071-greatest-common-divisor-of-strings.cpp
1 parent372e1c8 commit8fa1f27

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Time Complexity: O(n^2)
3+
* Space Complexity: O(1)
4+
*/
5+
6+
classSolution {
7+
public:
8+
stringgcdOfStrings(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+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp