Leetcode解题-Simplify Path

描述

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”.

分析

比较简单,用stack,注意corner cases。时间O(n),空间O(n)

代码

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""

ps = path.split('/')
ss = []
for p in ps:
if p == '.' or p == '':
continue
elif p == '..':
if len(ss) > 0:
ss.pop()
else:
ss.append(p)
return '/' + '/'.join(ss)

热评文章