Skip to content

Latest commit

 

History

History
54 lines (43 loc) · 1.82 KB

71. Simplify Path.md

File metadata and controls

54 lines (43 loc) · 1.82 KB

71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" path = "/a/../../b/../c//.//", => "/c" path = "/a//b////c/d//././/..", => "/a/b/c"

In a UNIX-style file system, a period ('.') refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki/Path_(computing)#Unix_style

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".

Solution

结合条件来看,/除了用作分隔符之外没有用处;.表示当前dir,也没有用;..表示返回上一个dir,从stack里面pop出最后一个,如果空的话就忽略(我觉得实际中不应该忽略的emm)。其余情况就push入栈。

最后用/把栈里面的东西连起来即可。

Code

class Solution:
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        list = path.split('/')
        stack = []
        output = ''
        for c in list:
            if len(c) == 0 or c == '.':
                continue
            elif c == '..':
                if len(stack) is not 0:
                    stack.pop()
            else:
                stack.append(c)
        if len(stack) == 0:
            output = '/'
        else:
            for c in stack:
                output += '/' + c
        # print(output)
        return output