Skip to content

Instantly share code, notes, and snippets.

@duglin
Created May 7, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duglin/c88c3d5fde9c9ac6fd22 to your computer and use it in GitHub Desktop.
Save duglin/c88c3d5fde9c9ac6fd22 to your computer and use it in GitHub Desktop.
findCommon
package main
import (
"fmt"
"path/filepath"
"strings"
)
func findCommon(paths []string) string {
sep := string(filepath.Separator)
res, resSep := "", ""
for i := 0; i < len(paths); i++ {
if res != "" && strings.HasPrefix(paths[i], resSep) {
continue
}
dir := paths[i]
for {
if dir == "" {
dir = sep
}
dir = filepath.Dir(dir)
if res == "" || dir == sep || strings.HasPrefix(resSep, dir+sep) {
res, resSep = dir, dir
if !strings.HasSuffix(resSep, sep) {
resSep += sep
}
break
}
}
}
return res
}
func main() {
fmt.Print(findCommon([]string{
"/a/b/c/d",
"/a/b/c/e",
}) + "\n")
fmt.Print(findCommon([]string{
"/a/b/c/d",
"/a/b/f/e",
}) + "\n")
fmt.Print(findCommon([]string{
"/a/b/c/d",
"/z/y/x/w",
}) + "\n")
fmt.Print(findCommon([]string{
"/a/b/c/d",
"/e",
}) + "\n")
fmt.Print(findCommon([]string{
"/a/b/c/d",
"/",
}) + "\n")
fmt.Print(findCommon([]string{
"/",
"/a/b/c/d",
}) + "\n")
fmt.Print(findCommon([]string{
"/a/b/c/d",
"/e/f/g",
}) + "\n")
fmt.Print(findCommon([]string{
"/a/b/c/d",
"",
}) + "\n")
fmt.Print(findCommon([]string{
"",
"/a/b/c/d",
}) + "\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment