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

Add: Greatest Common Divisor of Strings #733

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
awesee merged 1 commit into master from develop
Dec 9, 2019
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
View file Open in desktop
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
}
View file Open in desktop
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)
}
}
}

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