Skip to content

Commit 802d988

Browse files
feat: longest common prefix
1 parent 99e9150 commit 802d988

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

resolved/longest-common-prefix.go

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package resolved
2+
3+
import (
4+
"strings"
5+
)
6+
7+
func LongestCommonPrefix(strs []string) string {
8+
prefix := ""
9+
if len(strs) == 0 {
10+
return prefix
11+
}
12+
13+
for idx := range strs[0] {
14+
searchedPrefix := strs[0][:idx+1]
15+
16+
wordsListLength := len(strs)
17+
wordsWithPrefix := 0
18+
for _, word := range strs {
19+
if hasPrefix := strings.HasPrefix(word, searchedPrefix); hasPrefix {
20+
wordsWithPrefix++
21+
}
22+
}
23+
24+
if wordsWithPrefix == wordsListLength {
25+
prefix = searchedPrefix
26+
}
27+
}
28+
29+
return prefix
30+
}

0 commit comments

Comments
 (0)