MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / longestCommonPrefix

Function longestCommonPrefix

longest_common_prefix_14/solution.go:3–38  ·  view source on GitHub ↗
(strs []string)

Source from the content-addressed store, hash-verified

1package longest_common_prefix_14
2
3func longestCommonPrefix(strs []string) string {
4 if len(strs) == 0 {
5 return ""
6 }
7
8 // find min len string in strs
9 idx := 0
10 minLen := len(strs[idx])
11 for i, s := range strs {
12 if len(s) < minLen {
13 minLen = len(s)
14 idx = i
15 }
16 }
17
18 // for each char in min len string,
19 // see if every nth char in strs matches
20 // to build the longest common prefix.
21 lPrefix := ""
22 for i := 0; i < minLen; i++ {
23 allMatch := true
24 for j := 0; j < len(strs); j++ {
25 if strs[j][i] != strs[idx][i] {
26 allMatch = false
27 }
28 }
29
30 if allMatch {
31 lPrefix += string(strs[idx][i])
32 } else {
33 break
34 }
35 }
36
37 return lPrefix
38}

Callers 1

Test_longestCommonPrefixFunction · 0.85

Calls

no outgoing calls

Tested by 1

Test_longestCommonPrefixFunction · 0.68