-
Notifications
You must be signed in to change notification settings - Fork 0
/
071.go
45 lines (41 loc) · 807 Bytes
/
071.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
package p071
import (
"bytes"
)
/**
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
*/
func simplifyPath(path string) string {
stack := make([]string, 0)
bpath := []byte(path)
var buf bytes.Buffer
for i := 0; i <= len(bpath); i++ {
if i == len(bpath) || bpath[i] == '/' {
dir := buf.String()
buf.Reset()
if dir == "." || len(dir) == 0 {
continue
} else if dir == ".." {
if len(stack) > 0 {
stack = stack[:len(stack)-1]
}
} else {
stack = append(stack, dir)
}
} else {
buf.WriteByte(bpath[i])
}
}
buf.Reset()
if len(stack) == 0 {
stack = append(stack, "")
}
for _, dir := range stack {
buf.WriteByte('/')
buf.WriteString(dir)
}
return buf.String()
}