From f4596155b290d822075290acd2015a182a845c6e Mon Sep 17 00:00:00 2001 From: Jason Staten Date: Wed, 28 Sep 2022 00:50:16 -0600 Subject: [PATCH] longestprefix --- longestprefix/longestprefix.go | 28 ++++++++++++++++ longestprefix/longestprefix_test.go | 52 +++++++++++++++++++++++++++++ longestprefix/readme.md | 25 ++++++++++++++ 3 files changed, 105 insertions(+) create mode 100644 longestprefix/longestprefix.go create mode 100644 longestprefix/longestprefix_test.go create mode 100644 longestprefix/readme.md diff --git a/longestprefix/longestprefix.go b/longestprefix/longestprefix.go new file mode 100644 index 0000000..011f11b --- /dev/null +++ b/longestprefix/longestprefix.go @@ -0,0 +1,28 @@ +package longestprefix + +import ( + "strings" +) + +func LongestCommonPrefix(strs []string) string { + result := "" + + if len(strs) == 0 { + return result + } + + first := strs[0] + rest := strs[1:] + + for i := range first { + prefix := first[:i+1] + for _, s := range rest { + if !strings.HasPrefix(s, prefix) { + return result + } + } + result = prefix + } + + return first +} diff --git a/longestprefix/longestprefix_test.go b/longestprefix/longestprefix_test.go new file mode 100644 index 0000000..da6301f --- /dev/null +++ b/longestprefix/longestprefix_test.go @@ -0,0 +1,52 @@ +package longestprefix_test + +import ( + "testing" + + "git.jxs.me/leetgo/longestprefix" +) + +func TestEmpty(t *testing.T) { + expected := "" + result := longestprefix.LongestCommonPrefix([]string{}) + + if expected != result { + t.Errorf("%q != %q", expected, result) + } +} + +func TestSingle(t *testing.T) { + expected := "bark" + result := longestprefix.LongestCommonPrefix([]string{ + "bark", + }) + + if expected != result { + t.Errorf("%q != %q", expected, result) + } +} + +func TestSimple(t *testing.T) { + expected := "ye" + result := longestprefix.LongestCommonPrefix([]string{ + "yes", + "yeet", + }) + + if expected != result { + t.Errorf("%q != %q", expected, result) + } +} + +func TestExample(t *testing.T) { + expected := "fl" + result := longestprefix.LongestCommonPrefix([]string{ + "flower", + "flow", + "flight", + }) + + if expected != result { + t.Errorf("%q != %q", expected, result) + } +} diff --git a/longestprefix/readme.md b/longestprefix/readme.md new file mode 100644 index 0000000..af683fa --- /dev/null +++ b/longestprefix/readme.md @@ -0,0 +1,25 @@ +Write a function to find the longest common prefix string amongst an array of strings. + +If there is no common prefix, return an empty string "". + + + +Example 1: + +Input: strs = ["flower","flow","flight"] +Output: "fl" + +Example 2: + +Input: strs = ["dog","racecar","car"] +Output: "" +Explanation: There is no common prefix among the input strings. + + + +Constraints: + + 1 <= strs.length <= 200 + 0 <= strs[i].length <= 200 + strs[i] consists of only lowercase English letters. +