Created
May 7, 2015 14:21
-
-
Save duglin/c88c3d5fde9c9ac6fd22 to your computer and use it in GitHub Desktop.
findCommon
This file contains 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
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