diff --git a/problems/greatest-common-divisor-of-strings/greatest_common_divisor_of_strings.go b/problems/greatest-common-divisor-of-strings/greatest_common_divisor_of_strings.go index 99929972b..f22da6cbd 100644 --- a/problems/greatest-common-divisor-of-strings/greatest_common_divisor_of_strings.go +++ b/problems/greatest-common-divisor-of-strings/greatest_common_divisor_of_strings.go @@ -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 -} diff --git a/problems/greatest-common-divisor-of-strings/greatest_common_divisor_of_strings_test.go b/problems/greatest-common-divisor-of-strings/greatest_common_divisor_of_strings_test.go new file mode 100644 index 000000000..75fe7869c --- /dev/null +++ b/problems/greatest-common-divisor-of-strings/greatest_common_divisor_of_strings_test.go @@ -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) + } + } +}