python simple solution by using stack


  • 0
    C
    1. split the path by "/"
    2. when the element meet "..", pop the stack when length > 0
    3. ignore "." and "", push others into stk.
    4. join the list to path string.
    class Solution(object):
        def simplifyPath(self, path):
            """
            :type path: str
            :rtype: str
            """
            dir_list = path.split("/")
            stk = []
            for dire in dir_list:
                if dire == "..":
                    if len(stk)>0:
                        stk.pop()
                elif dire != "." and len(dire)>0:
                    stk.append(dire)
            
            return "/"+"/".join(stk)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.