[LeetCode-JAVA] Simplify Path

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

思路:用Stack完成检测,取出两个"/""/"之间的内容,做出如下判断:

/../ : 返回上一级菜单,即栈size大于1的时候,说明上一级菜单不为空,弹出。

/./ 或者 // 什么都不做,继续循环。

正常情况,压入文件夹名和"/"。

注意:每次循环之后进行内容和"/"的插入,防止过多的判断和弹出操作。

public class Solution {
    public String simplifyPath(String path) {
        Stack<String> stack = new Stack<String>();
        stack.push("/");
        
        char flag = '/';
        
        for(int i = 1 ; i < path.length() ; i++){
            int cur = i;
            while(i < path.length() && path.charAt(i) != flag){
                i++;
            }
            String temp = path.substring(cur, i); //取出内容
            
            if(temp.equals("..")){
                if(stack.size() > 1){
                    stack.pop();
                    stack.pop();
                }
                continue;
            }
            if(temp.equals(".") || temp.equals("")){
                continue;
            }
            stack.push(temp);
            stack.push("/");
        }
        if(stack.size() == 1) 
            return "/";
        
        String req = "";
        while(!stack.isEmpty()){
            req = stack.pop() + req;
        }
        return req.substring(0,req.length()-1);  //去掉最后的/
    }
}
原文地址:https://www.cnblogs.com/TinyBobo/p/4505306.html