-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsimplifyPath.go
More file actions
86 lines (71 loc) · 1.64 KB
/
Copy pathsimplifyPath.go
File metadata and controls
86 lines (71 loc) · 1.64 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*https://leetcode.com/problems/simplify-path/description/
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".
*/
package lstack
import (
"github.com/TTWShell/algorithms/data-structure/stack" // need copy stack.go when run in leetcode online
"strings"
)
func simplifyPath(path string) string {
s := stack.Constructor()
paths := strings.Split(path, "/")
for _, sub := range paths {
if sub == "." || sub == "" {
continue
} else if sub == ".." {
if !s.IsEmpty() {
s.Pop()
}
} else {
s.Push(sub)
}
}
if length := s.Len(); length > 0 {
res, idx := make([]string, length, length), length-1
for !s.IsEmpty() {
res[idx] = s.Pop().(string)
idx--
}
return "/" + strings.Join(res, "/")
}
return "/"
}
/*
type Stack struct {
stack []interface{}
len int
}
func Constructor() *Stack {
s := &Stack{}
s.stack = make([]interface{}, 0)
s.len = 0
return s
}
func (s *Stack) Len() int {
return s.len
}
func (s *Stack) IsEmpty() bool {
return s.len == 0
}
func (s *Stack) Pop() (element interface{}) {
element, s.stack = s.stack[0], s.stack[1:]
s.len--
return
}
func (s *Stack) Push(element interface{}) {
prepend := []interface{}{element}
s.stack = append(prepend, s.stack...)
s.len++
}
func (s *Stack) Top() interface{} {
return s.stack[0]
}
*/