首页 > 代码库 > 71. Simplify Path

71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

click to show corner cases.

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

/**
* 这是一道简化路径的题,路径简化的依据是:

当遇到“/../"则需要返回上级目录,需检查上级目录是否为空。

当遇到"/./"则表示是本级目录,无需做任何特殊操作。

当遇到"//"则表示是本级目录,无需做任何操作。

当遇到其他字符则表示是文件夹名,无需简化。

当字符串是空或者遇到”/../”,则需要返回一个"/"。

当遇见"/a//b",则需要简化为"/a/b"。
*
*/

Use two stack

public class Solution {
    public String simplifyPath(String path) {
        String[] p = path.split("/");
        Stack<String> stack = new Stack<String>();
        for(int i = 0 ; i < p.length ; i ++){
         if(p[i].length() == 0 || p[i].equals(".")) continue;
         else if(p[i].equals("..")){
             if(!stack.isEmpty()) stack.pop();
         }
         else stack.push(p[i]);
        }
        StringBuilder sb = new StringBuilder();
        if(stack.isEmpty()) return "/";
        
        Stack<String> temp = new Stack<String>();
        while(!stack.isEmpty()){
            temp.push(stack.pop());
        }
        
        while(!temp.isEmpty()){
            sb.append("/").append(temp.pop());
        }
        
        return sb.toString();
    }
}

 

71. Simplify Path