Created
August 30, 2021 14:17
-
-
Save t-eckert/5bfcb5d245ea8f355ffe5f3e3ac152d6 to your computer and use it in GitHub Desktop.
Solution to the latest cassidoo challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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