码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode------Simplify Path

时间:2015-04-09 23:12:36      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

标题:

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)

 

leetcode------Simplify Path

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4412247.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!