zoukankan      html  css  js  c++  java
  • [Leetcode]@python 71. Simplify Path

    题目链接

    https://leetcode.com/problems/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".

    题目大意

    简化Unix系统的文件访问路径

    解题思路

    先根据‘/’对字符串进行切割,用栈对路径名进行存储,若遇到路径名,则入栈;若遇到“..”,则将栈顶元素pop出来;最后将栈内剩余的元素用“/”连接后输出

    代码

    class Solution(object):
        def simplifyPath(self, path):
            """
            :type path: str
            :rtype: str
            """
            stack = []
            i = 0
            ans = ''
            while i < len(path):
                end = i + 1
                while end < len(path) and path[end] != '/':
                    end += 1
                sub = path[i + 1:end]
                if len(sub) > 0:
                    if sub == '..':
                        if stack != []:
                            stack.pop()
                    elif sub != '.':
                        stack.append(sub)
                i = end
            if stack == []:
                return '/'
            for i in stack:
                ans += '/' + i
            return ans
            
    
  • 相关阅读:
    Zookeeper数据类型
    Zookeeper基本命令
    Redis集群
    Mysql 模拟自增主键
    git回滚版本操作
    Redis缓存穿透和雪崩
    日期格式jackson格式化
    Zookeeper安装
    redis主从复制
    Redis哨兵模式
  • 原文地址:https://www.cnblogs.com/slurm/p/5130580.html
Copyright © 2011-2022 走看看