[Leetcode] 71. Simplify Path 解题报告

本文介绍了一个用于简化Unix风格文件路径的算法实现。通过解析输入路径并应用特定规则,如忽略当前目录(.)和返回上级目录(..),该算法能够有效简化路径表达。文章详细解释了路径构成规则,并提供了一段C++代码示例。

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

题目

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

click to show corner cases.

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

思路

首先熟悉一下Unix-style的路径构成规则:

字符 含义(英文) 含义(中文)
/ root directory 根目录
/ Directory Separator 路径分隔符
. Current Directory 当前目录
.. Parent Directory 上级目录
~ Home Directory 家目录
有了上述规则,就可以设计本题的思路:1)如果当前目录为“..”,则代表要返回上一层目录,所以将当前目录从结果中删除;2)如果当前目录是空或者".",代表该目录无意义,可以直接抛弃;3)如果是合法目录,则加入当前结果中。

实现技巧:1)可以在path的最后加入一个"/",这样可以统一提取两个“/”之间的字符串,简化程序逻辑;2)采用vector来模拟stack,因为vector除了具备stack的所有功能之外,还有从前到后顺序访问元素的优势,这样可以避免最后对stack中的元素进行反转的额外时间复杂度开销。

代码

class Solution {
public:
    string simplifyPath(string path) {
        vector<string> st;      // we use vecctor to simulate stack 
        path += '/';            // for easier programming
        for (int i = 1; i < path.size(); i++) {  
            int pos = path.find('/', i);  
            string tem = path.substr(i, pos - i);  
            if (tem == "..") {  
                if(st.size() > 0) {
                    st.pop_back();  
                }
            }  
            else if (tem.size() > 0 && tem != ".") {
                st.push_back("/" + tem);  
            }
            i = pos;  
        }  
        string ans;  
        for (auto val: st) {
            ans += val; 
        }
        return ans.size() == 0? "/" : ans;  
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值