LeetCode-Simplify Path

本文详细解释了如何通过栈操作来简化Unix路径,利用栈来处理路径中的特殊符号,如'..'和'.',实现路径的高效压缩。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个题只要搞清楚什么是unix的path格式就好 就是后面没有/   除了字母等有意义的字符以外 只有..有用 就是向上的意思

所以用stack 不是..也不是无用的就push 遇到..就pop

最后把stack里面的连起来 注意corner case 就是stack为空 但是遇到了。。 无法pop

但是也要忽略。。

public class Solution {
    public String simplifyPath(String path) {
        if ( path == null || path.length() == 0 )
            return "";
        Stack <String> stack = new Stack <String> ();
        for ( String str : path.split("/") ){
            if ( str.equals("") || str.equals(".") || ( stack.isEmpty() && str.equals("..") ))
                continue;
            else if ( !stack.isEmpty() && str.equals("..") )
                stack.pop();
            else
                stack.push( str );
        }
        if ( stack.isEmpty () ) 
            return "/";
        String res = "";
        while ( !stack.isEmpty() ){
            res = "/" + stack.pop() + res;
        }
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值