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)