Leetcode——71. Simplify Path

本文针对LeetCode中的简化路径问题提供了解决方案。介绍了如何利用栈结构处理Unix风格的文件绝对路径,实现路径的规范化,包括忽略冗余斜杠、处理上级目录等特殊情况。

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

题目原址

https://leetcode.com/problems/simplify-path/description/

题目描述

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

解题思路

给定一个绝对路径,将其化为最简的形式返回来。使用栈来完成这道题,这里有几个特殊的情况:

  • 如果是“.”或者空,则保持不动,因为表示的是当前的路径
  • 如果是“..”,则说明要返回上级菜单,因此需要从栈中弹出元素
  • 除了上述两种情况,其他的情况就直接压栈就可以了

AC代码

class Solution {
    public String simplifyPath(String path) {

        Stack<String> stack = new Stack<>();
        while(path.length() > 0) {
            int start = path.indexOf("/");  //当前字符串的第一个/位置
            path = path.substring(start + 1); //将当前字符串的第一个/去掉
            int end = path.indexOf("/"); //当前字符串的第二个/位置

            if(end == -1) {   //如果字符串已经没有/了,则将字符串末尾位置置于字符串尾
                end = path.length();
            }   
            String part = path.substring(0, end);  //取得两个//中间的字符串
            path = path.substring(end); //更新path的值,其值等于第二个/后面的元素的值

            if(part.equals("") || part.equals(".")) // 如果中间的字符串为空或者为.则什么都不做
                continue;
            if(part.equals("..")){ //如果中间的字符串为..,则表示返回上级菜单,所以要从栈中弹出栈顶元素
                if(!stack.isEmpty())
                    stack.pop();
            }else {
                stack.push("/" + part); //否则,将中间的字符串压入栈中
            }
        }
       String ret = "";
        while(!stack.isEmpty()) {
            ret = stack.pop() + ret;
        }
        if(ret.length() == 0)
            ret = "/";
        return ret;      
    }
}

感谢

https://blog.youkuaiyun.com/MebiuW/article/details/51399770

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值