zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):071-Simplify Path

    题目来源:

      https://leetcode.com/problems/simplify-path/


    题意分析:

      简化Unix上的绝对路径,也就是多个'/'代表一个,'..'表示返回上一级目录,‘.'代表当前目录。


    题目思路:

      利用栈,把非'/'和'.'push进栈,如果遇到'..'pop掉一个,否则继续push进去。最后还原成路径格式。


    代码(Python):

      

    class Solution(object):
        def simplifyPath(self, path):
            """
            :type path: str
            :rtype: str
            """
            stack,i,ans = [],0,''
            while i < len(path):
                j = i + 1
                while j < len(path) and path[j] != '/':
                    j += 1
                tmp = path[i + 1:j]
                if tmp != '':
                    if tmp == '..':
                        if stack !=[]:
                            stack.pop()
                    elif tmp != '.':
                        stack.append(tmp)
                i = j
            if stack == []:
                return '/'
            for k in stack:
                ans += '/' + k
            return ans
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/5069660.html

  • 相关阅读:
    HackerRank
    HackerRank
    HackerRank
    LeetCode "Bitwise AND of Numbers Range"
    HackerRank
    HackerRank
    LeetCode "Binary Tree Right Side View"
    HihoCoder
    HihoCoder
    HackerRank
  • 原文地址:https://www.cnblogs.com/chruny/p/5069660.html
Copyright © 2011-2022 走看看