Created
June 4, 2021 21:16
-
-
Save gammazero/6e0265fb1f6ebce9e752ef9ec449dcb1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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