Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,36 +1,17 @@
package problem1071

import "strings"

func gcdOfStrings(s1, s2 string) string {
l1, l2 := len(s1), len(s2)
d := gcd(max(l1, l2), min(l1, l2))
p := s2[:d]
if s1 == strings.Repeat(p, l1/d) &&
s2 == strings.Repeat(p, l2/d) {
return p
func gcdOfStrings(str1 string, str2 string) string {
if str1+str2 != str2+str1 {
return ""
}
return ""
return str1[:gcd(len(str1), len(str2))]
}

// a >= b
// 最大公约数(Greatest Common Divisor)缩写为GCD
// 辗转相除法
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}

func min(a, b int) int {
if a < b {
return a
}
return b
}

func max(a, b int) int {
if a > b {
return a
}
return b
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package problem1071

import "testing"

type testType struct {
str1 string
str2 string
want string
}

func TestGcdOfStrings(t *testing.T) {
tests := [...]testType{
{
str1: "ABCABC",
str2: "ABC",
want: "ABC",
},
{
str1: "ABABAB",
str2: "ABAB",
want: "AB",
},
{
str1: "LEET",
str2: "CODE",
want: "",
},
}
for _, tt := range tests {
got := gcdOfStrings(tt.str1, tt.str2)
if got != tt.want {
t.Fatalf("in: %v, got: %v, want: %v", tt.str1, got, tt.want)
}
}
}