leetcode笔记--Simplify Path

题目:难度(Medium)

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".
Tags:Stack String

分析:这道题我提交了很多次才AC,主要是由于对于题目认为”pass“的输出,觉得他定义给的不够清楚,导致修改了很多次。感觉没太大意义,除了用到了栈,下面我根据他的testcase,给几组我出过错的输入输出,帮助大家理解题目的”正确目的“。


代码实现:

class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        #stack列表用来维护一个栈,栈里放单独的路径名
        stack = []
        i = 0
        #dirTmp用来存储每一个单独的路径名字
        dirTmp = ""
        while i < len(path):   
            if path[i] == '/':
                #遇到'/'则要开始考虑是否要将一个路径名入栈或出栈
                if dirTmp != "":
                    if dirTmp == "..":
                        if len(stack) != 0:
                            stack.pop()
                    elif dirTmp == ".":
                        pass
                    else:
                        #路径名不是'.'(跳过)或者'..'(上级),则是一个真正的路径名,入栈
                        stack.append(dirTmp)
                    #处理完路径名,置空,为下一次做准备
                    dirTmp = ""
            else:
                #不是'/',则组成“路径名”
                dirTmp += path[i]
            i += 1  
        #若结尾处不是'/',则可能遗留下最后一个路径名,还需要处理 
        if dirTmp == "..":
            if len(stack) != 0:
                stack.pop()
            dirTmp = ""
        if dirTmp != "" and dirTmp != ".":
            stack.append(dirTmp)
        return "/" + "/".join(stack)

你可能感兴趣的:(LeetCode,python,String,stack)