Before doing this problem, you have to know about unix-style. The '. .' means going back one level, and '.' means doing nothing, and others mean going deep.
Using stack operation is a good way to solve. Or we can attack from string operation.
Solution 1:
# T:O(n) S:O(n)
class Solution:
# @param path, a string
# @return a string
def simplifyPath(self, path):
stack, tokens = [], path.split("/")
for token in tokens:
if token == ".." and stack:
stack.pop()
elif token != ".." and token != "." and token:
stack.append(token)
return "/" + "/".join(stack)
Run Time: 48 msSolution 2:
# T:O(n) S:O(n)
class Solution:
# @param {string} path
# @return {string}
def simplifyPath(self, path):
path = path.split('/')
cur = '/'
for i in path:
if i == '..':
# back to upper level
if cur != '/':
cur = '/'.join(cur.split('/')[:-1])
# if upper level exist, roll back by one level
if cur == '':
cur = '/'
elif i != '.' and i != '': # add one level
if cur == '/':
cur += i
else:
cur += '/' + i
return cur
Run Time: 60 ms
No comments:
Post a Comment