parent
943c558f8f
commit
f4596155b2
@ -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
|
||||||
|
}
|
@ -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)
|
||||||
|
}
|
||||||
|
}
|
@ -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.
|
||||||
|
|
Loading…
Reference in new issue