forked from TonnyL/Windary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimplifyPath.go
47 lines (40 loc) · 1015 Bytes
/
SimplifyPath.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package SimplifyPath
import "strings"
//Given an absolute path for a file (Unix-style), simplify it.
//
//For example,
//path = "/home/", => "/home"
//path = "/a/./b/../../c/", => "/c"
//
//Corner Cases:
//Did you consider the case where path = "/../"?
//In this case, you should return "/".
//Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
//In this case, you should ignore redundant slashes and return "/home/foo".
//
//Accepted.
func simplifyPath(path string) string {
pathLength := len(path)
if pathLength == 0 {
return path
}
strs, results := strings.Split(path, "/"), make([]string, 0)
for _, s := range strs {
if s == ".." {
if len(results) != 0 {
results = append(results[:len(results)-1], results[len(results):]...)
}
} else if (s != ".") && len(s) != 0 {
results = append(results, s)
}
}
if len(results) == 0 {
return "/"
}
s := ""
for i := 0; i < len(results); i++ {
s += "/"
s += results[i]
}
return s
}