leetcode: 71. Simplify Path

来源:互联网 发布:二手玫瑰知乎 编辑:程序博客网 时间:2024/06/04 23:36

Q

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

AC

class Solution(object):    def simplifyPath(self, path):        """        :type path: str        :rtype: str        """        # 思路:        # 1. split / 形成List        # 2. 如果 .. 就 pop 前面的        # 3. 还要考虑 '///' '/...'        places = [p for p in path.split("/") if p!="." and p!=""]        stack = []        for p in places:            if p == "..":                if len(stack) > 0:                    stack.pop()            else:                stack.append(p)        return "/" + "/".join(stack)# Time:  O(n)# Space: O(n)class Solution2(object):    def simplifyPath(self, path):        stack, tokens = [], path.split("/")        for token in tokens:            if token == ".." and stack:                stack.pop()            elif token != ".." and token != "." and token:                stack.append(token)        return "/" + "/".join(stack)if __name__ == "__main__":    assert Solution().simplifyPath("/../") == '/'    assert Solution().simplifyPath("/home//foo/") == '/home/foo'


原创粉丝点击