简化路径 (Simplify Path)

 

思路:栈

// @Title: 简化路径 (Simplify Path)
// @Author: qisiii
// @Date: 2024-10-13 16:43:36
// @Runtime: 4 ms
// @Memory: 42.5 MB
// @comment: 栈
// @flag: BLUE
class Solution {
    public String simplifyPath(String path) {
        String[] paths=path.split("\\/");
        Stack<String> stack=new Stack();
        for(int i=0;i<paths.length;i++){
            String cur=paths[i];
            if(cur.length()<=0||cur.equals(".")){
                continue;
            }else if(cur.equals("..")){
                if(!stack.isEmpty()){
                    stack.pop();
                }
            }else{
                stack.push(paths[i]);
            }
        }
        if(stack.isEmpty()){
            return "/";
        }
        StringBuilder build=new StringBuilder();
        while(!stack.isEmpty()){
            build.insert(0,stack.pop()).insert(0,"/");
        }
        return build.toString();
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18