[leetcode] 71. Simplify Path @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/88050581

原题

Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period … moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix

Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.

Example 1:

Input: “/home/”
Output: “/home”
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:

Input: “/…/”
Output: “/”
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:

Input: “/home//foo/”
Output: “/home/foo”
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:

Input: “/a/./b/…/…/c/”
Output: “/c”
Example 5:

Input: “/a/…/…/b/…/c//.//”
Output: “/c”
Example 6:

Input: “/a//b////c/d//././/…”
Output: “/a/b/c”

解法

堆栈. 题意说一个句号代表当前目录, 两个句号代表上一个目录, 结果要求以"/“开头, 两个目录之间用”/"连接.

涉及目录的题大多用栈处理, 我们用split()方法将path中的’/‘去掉并且转化为列表, 然后遍历列表, 遇到空字符串或者一个句号则直接忽略, 遇到两个句号则出栈, 其他情况则进栈, 最后将列表转化为字符串并用’/'连接, 开头加上"/".

代码

class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        stack = []
        path = path.split('/')
        for p in path:
            if p == '' or p == '.':
                continue
            elif p == '..':
                if stack:
                    stack.pop()
            else:
                stack.append(p)
                
        return '/' + '/'.join(stack)

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/88050581