Title: Simplify Path Source: leetcode.com
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 solution
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 |
''' https://leetcode.com/problems/simplify-path/ ''' class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ dirs = path.split("/") p = "/" for dir in dirs: #print dir, p if (dir == '') or (dir == '.'): continue if dir == '..': #print p, p.index('/',-1) p = p[:p.rindex('/')] if p == '': p = '/' continue if p[-1] != '/': p += '/' + dir else: p += dir return p |