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

Commit af12ddd

Browse files
author
Shuo
authored
Merge pull request #733 from openset/develop
Add: Greatest Common Divisor of Strings
2 parents b77889f + 633a237 commit af12ddd

File tree

2 files changed

+41
-25
lines changed

2 files changed

+41
-25
lines changed
Lines changed: 6 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,17 @@
11
package problem1071
22

3-
import "strings"
4-
5-
func gcdOfStrings(s1, s2 string) string {
6-
l1, l2 := len(s1), len(s2)
7-
d := gcd(max(l1, l2), min(l1, l2))
8-
p := s2[:d]
9-
if s1 == strings.Repeat(p, l1/d) &&
10-
s2 == strings.Repeat(p, l2/d) {
11-
return p
3+
func gcdOfStrings(str1 string, str2 string) string {
4+
if str1+str2 != str2+str1 {
5+
return ""
126
}
13-
return ""
7+
return str1[:gcd(len(str1), len(str2))]
148
}
159

16-
// a >= b
10+
// 最大公约数(Greatest Common Divisor)缩写为GCD
11+
// 辗转相除法
1712
func gcd(a, b int) int {
1813
if b == 0 {
1914
return a
2015
}
2116
return gcd(b, a%b)
2217
}
23-
24-
func min(a, b int) int {
25-
if a < b {
26-
return a
27-
}
28-
return b
29-
}
30-
31-
func max(a, b int) int {
32-
if a > b {
33-
return a
34-
}
35-
return b
36-
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package problem1071
2+
3+
import "testing"
4+
5+
type testType struct {
6+
str1 string
7+
str2 string
8+
want string
9+
}
10+
11+
func TestGcdOfStrings(t *testing.T) {
12+
tests := [...]testType{
13+
{
14+
str1: "ABCABC",
15+
str2: "ABC",
16+
want: "ABC",
17+
},
18+
{
19+
str1: "ABABAB",
20+
str2: "ABAB",
21+
want: "AB",
22+
},
23+
{
24+
str1: "LEET",
25+
str2: "CODE",
26+
want: "",
27+
},
28+
}
29+
for _, tt := range tests {
30+
got := gcdOfStrings(tt.str1, tt.str2)
31+
if got != tt.want {
32+
t.Fatalf("in: %v, got: %v, want: %v", tt.str1, got, tt.want)
33+
}
34+
}
35+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /