Skip to content

Instantly share code, notes, and snippets.

@t-eckert
Created August 30, 2021 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t-eckert/5bfcb5d245ea8f355ffe5f3e3ac152d6 to your computer and use it in GitHub Desktop.
Save t-eckert/5bfcb5d245ea8f355ffe5f3e3ac152d6 to your computer and use it in GitHub Desktop.
Solution to the latest cassidoo challenge
package longest
func longestPrefix(words []string) string {
if len(words) == 0 {
return ""
}
common := make([]rune, 0, len(words[0]))
for i, letter := range words[0] {
for _, word := range words[0:] {
if letter != rune(word[i]) {
return string(common)
}
}
common = append(common, letter)
}
return string(common)
}
package longest
import "testing"
func TestLongestPrefix(t *testing.T) {
params := []struct {
words []string
expected string
}{
{[]string{"cranberry", "crawfish", "crap"}, "cra"},
{[]string{"parrot", "poodle", "fish"}, ""},
{[]string{}, ""},
{[]string{"fore", "fore", "fore"}, "fore"},
}
for _, param := range params {
actual := longestPrefix(param.words)
if param.expected != actual {
t.Logf("given: %s\nexpected: %s\nactual: %s\n", param.words, param.expected, actual)
t.Fail()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment