Skip to content

Instantly share code, notes, and snippets.

@gammazero
Created June 4, 2021 21:16
Show Gist options
  • Save gammazero/6e0265fb1f6ebce9e752ef9ec449dcb1 to your computer and use it in GitHub Desktop.
Save gammazero/6e0265fb1f6ebce9e752ef9ec449dcb1 to your computer and use it in GitHub Desktop.
// longestCommonPrefix returns the string in compares that has the longest common prefix with s
func longestCommonPrefix(s string, compares ...string) string {
var longestMatched int
var longestCmp string
maxLength := len(s)
for _, c := range compares {
cmpLen := len(c)
if cmpLen > maxLength {
cmpLen = maxLength
}
if cmpLen <= longestMatched {
// Already have a longer match, so skip this
continue
}
matched := cmpLen
for i := 0; i < cmpLen; i++ {
if c[i] != s[i] {
matched = i
break
}
}
if matched > longestMatched {
// Record longest match seen yet
longestCmp = c
if matched == maxLength {
// Found longest possible match; done
break
}
longestMatched = matched
}
}
return longestCmp
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment