leetcode专题训练 71. Simplify Path

这道题是将绝对路径转化为最简路径的题。由于路径中的’/‘是用来分割文件名和.操作的,所以先用split函数将路径用’/'分割。分割好路径后,就处理.和…操作即可。由于…操作是返回上一层,也就是将当前路径中最后文件名弹出,所以用一个栈来存储所有文件名。由于python中的list可以直接实现栈的操作,所以定义了CanoList来记录所有的文件名。如果遇到…操作,那么就弹出最后的文件名,如果遇到.操作,就继续。之后CanoList中的文件名就为结果的文件名。将List转为以/衔接的字符串即可。

class Solution:
    def simplifyPath(self, path: str) -> str:
        PathList = path.split("/")
        CanoList = [] # define a list for the output path
        for Name in PathList:
            if Name == "":
                continue
            if Name == '.':
                continue
            if Name == "..":
                if CanoList:
                    CanoList.pop() # delete the last folder name
                continue
            CanoList.append(Name)
        result = ""
        for Name in CanoList:
            result += "/"
            result += Name
        # print(CanoList)
        if not CanoList:
            result += "/"
        return result
                
发布了219 篇原创文章 · 获赞 28 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Ema1997/article/details/104149105