Simple python solution by using Stack.

  • 0

    We notice that if the path has "..", then it will remove the last director. so we can use Stack to solve the problem.
    here is python solution step:

    1. Split the string into list divide by "/". So we get all of the director elements.
            dir_list = path.split("/")
    1. Iterate the dir_list and push them into the stack. here are some rules:
      1. if the director is "..", we pop the stack if the length of the stack is larger than 0.
      2. we push the director into the stack if the director not equal "." and the length is larger than 0. This also means we ignore the director which is "." or the length equals 0.
            stack = []
            for director in dir_list:
                if director == "..":   # rule one
                    if len(stack)>0:     # pop if length > 0
                elif director != "." and len(director)>0:   # rule two
    1. Finally, we generate the path string by using join. For the start of the string will miss "/", we must put "/" on the begin.
            return "/"+"/".join(stack)

Log in to reply

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