-
Notifications
You must be signed in to change notification settings - Fork 20
/
SimplifyPath.py
65 lines (52 loc) · 1.5 KB
/
SimplifyPath.py
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
# -*- coding: UTF-8 -*-
#
# 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".
#
# Python, Python all accepted.
class SimplifyPath:
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
if len(path) == 0:
return path
strings = path.split("/")
stack = Stack()
for i in range(len(strings)):
if strings[i] == '..':
if not stack.isEmpty():
stack.pop()
elif strings[i] != '.' and strings[i] != '':
stack.push(strings[i])
string = ""
stack.items.reverse()
for i in range(len(stack.items)):
string += "/"
string += stack.items[i]
if len(string) == 0:
return "/"
return str(string)
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.insert(0, item)
def pop(self):
return self.items.pop(0)
def peek(self):
return self.items[0]
def size(self):
return len(self.items)