[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

原文地址:https://www.cnblogs.com/chruny/p/5069660.html