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:
- Split the string into list divide by "/". So we get all of the director elements.
dir_list = path.split("/")
- Iterate the dir_list and push them into the stack. here are some rules:
- if the director is "..", we pop the stack if the length of the stack is larger than 0.
- 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 stack.pop() elif director != "." and len(director)>0: # rule two stack.append(director)
- Finally, we generate the path string by using join. For the start of the string will miss "/", we must put "/" on the begin.