zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    Picture Control点击事件
    在C/C++中获取可执行文件的图标和信息
    C++获取系统图标方法
    C++ Vector 使用总结
    C++中vector和list的区别
    STL STD::list使用说明
    演示My97 DatePicker过程中的错误
    HTML5的语法变化
    利用 ACE 来实现 UDP 通讯
    VS2010中“工具>选项中的VC++目录编辑功能已被否决”解决方法
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4412247.html
Copyright © 2011-2022 走看看