71. Simplify Path | Java最短代码实现

本文深入探讨了简化路径问题,通过栈的基本操作实现路径简化。详细解释了算法逻辑,包括跳过分隔符、记录文件名及处理特殊指令,最终得到简化后的路径。
原题链接:71. Simplify Path

【思路】

本题考查字符串和栈的基本操作。本身并不难:

    public String simplifyPath(String path) {
        Stack<String> stack = new Stack<String>();
        String temp = "";
        for (int i = 0; i < path.length(); i++) {
            while (i < path.length() && path.charAt(i++) == '/')  //跳过'/'
                i++;
            while (i < path.length() && path.charAt(i) != '/') {  //将文件名记录在temp中
                temp += path.charAt(i);
                i++;
            }
            if (temp.equals("..") && !stack.isEmpty())  //如果为"..",且栈不空,弹出第一个(返回上一级目录)
                stack.pop();
            else if (!temp.equals(".") && !temp.equals("..") && !temp.equals(""))  //入栈
                stack.add(temp);
            temp = "";
        }
        while (!stack.isEmpty())
            temp = "/" + stack.pop() + temp;
        return temp == "" ? "/" : temp;
    }
252 / 252  test cases passed. Runtime: 11 ms  Your runtime beats 63.37% of javasubmissions.
欢迎优化!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值