leetcode------Simplify Path

标题:

Simplify Path

通过率: 20.1%
难度: 中等

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

click to show corner cases.

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

这个题要了解linux文件命令,“..”意思是返回上级,"."或者空""是本级的意思,

那么将path分片遇到"."或者""跳过,遇到".."弹栈,其他情况进栈,

还要一种情况就是path本身就是空,那么在整个循环结束够进栈一个空值。

代码如下:

 1 class Solution:
 2     # @param path, a string
 3     # @return a string
 4     def simplifyPath(self, path):
 5         pathSplit=path.split("/")
 6         stack=[]
 7         res=""
 8         for i in range(len(pathSplit)):
 9             if pathSplit[i] =="." or len(pathSplit[i])==0 :
10                 continue;
11             elif pathSplit[i] =="..":
12                 if len(stack)!=0:
13                     stack.pop()
14             else: stack.append(pathSplit[i])
15         if len(stack)==0:
16             stack.append("")
17         while len(stack)!=0:
18             res+="/"+stack.pop(0)
19         return res
20         

 

简化版:

 1 class Solution:
 2     # @param path, a string
 3     # @return a string
 4     def simplifyPath(self, path):
 5         pathSplit=path.split("/")
 6         stack=[]
 7         for ps in pathSplit:
 8             if ps !="." and ps!=".." and ps :
 9                 stack.append(ps)
10             elif ps ==".." and stack :
11                     stack.pop()
12         return "/"+"/".join(stack)

 

posted @ 2015-04-09 21:27  pku_smile  阅读(197)  评论(0编辑  收藏  举报