Skip to content

Commit 0f0862f

Browse files
solved longest common prefix
1 parent ecd6be4 commit 0f0862f

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package longestcommonprefix
2+
3+
func LongestCommonPrefix(strs []string) string {
4+
if len(strs) == 0 {
5+
return ""
6+
}
7+
if len(strs) == 1 {
8+
return strs[0]
9+
}
10+
i := 0
11+
b := false
12+
var str string
13+
for {
14+
var code string
15+
var waitCompare string
16+
for k, word := range strs {
17+
if k == 0 {
18+
if len(word) <= i {
19+
b = true
20+
break
21+
}
22+
waitCompare = string(word[i])
23+
} else {
24+
if len(word) <= i {
25+
b = true
26+
break
27+
}
28+
code = string(word[i])
29+
if code != waitCompare {
30+
b = true
31+
break
32+
}
33+
}
34+
}
35+
if b {
36+
break
37+
}
38+
waitCompare = code
39+
str += waitCompare
40+
i++
41+
}
42+
return str
43+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package longestcommonprefix_test
2+
3+
import (
4+
lcf "letcode/longest-common-prefix"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
func TestXxx(t *testing.T) {
11+
testCases := []struct {
12+
Name string
13+
Word []string
14+
Expectation string
15+
}{
16+
{
17+
Name: "Test 1",
18+
Word: []string{"flower", "flow", "flight"},
19+
Expectation: "fl",
20+
}, {
21+
Name: "Test 2",
22+
Word: []string{"aku", "kamu", "kita"},
23+
Expectation: "",
24+
}, {
25+
Name: "Test 3",
26+
Word: []string{"aku", "aku", "aku"},
27+
Expectation: "aku",
28+
}, {
29+
Name: "Test 4",
30+
Word: []string{"", "", ""},
31+
Expectation: "",
32+
},
33+
}
34+
35+
for _, testCase := range testCases {
36+
t.Run(testCase.Name, func(t *testing.T) {
37+
actual := lcf.LongestCommonPrefix(testCase.Word)
38+
assert.Equal(t, testCase.Expectation, actual)
39+
})
40+
}
41+
}

0 commit comments

Comments
 (0)