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.

Tips and Divergent thinking:

N/A

(全文完,原创文章,转载时请注明作者和出处)


(转载本站文章请注明作者和出处 烟客旅人 sigmainfy — http://www.sigmainfy.com,请勿用于任何商业用途)

Written on May 20, 2013