leetcode: Simplify Path

Problem Description:

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".

Solution and Precautions:

Using a stack to store all the names, when encountering “..”, then pop out the stack, when encountering a regular name, push the name into the stack, when encountering “.” or other characters, just ignore and continue scanning the path. After finishing scanning, just print the remaining names in the stack, note in unix, a path always start from “/”, followed by the name structure in the stack, and don’t append “/” in the last name in the stack.

Written on May 20, 2013