LeetCode 71. Simplify Path

本文介绍了一个简化Unix风格绝对路径的算法实现。通过栈结构处理特殊符号如'.'和'..',忽略多余的斜杠,最终得到规范化的路径字符串。

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

71. Simplify Path
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风格的绝对路径,返回简化后的结果~
分析:以"/"为分隔,将所有不是"."和".."的字符串放入栈中。如果是".."并且上一层不为空,就返回上一层,也就是弹栈;如果是".",不处理;如果有多个连续的"/",则只认一个"/":
从头到尾遍历字符串,如果是"/"就不断跳过;当不是"/"的时候,将后面的字符串放入temp中,如果是".."就弹栈,如果不是".."和"."就把temp压入栈中。
最后将栈中所有的元素按照"/"分隔连接成result字符串~

class Solution {
public:
    string simplifyPath(string path) {
        stack<string> s;
        string result = "", temp = "";
        int i = 0, len = path.length();
        while (i < len) {
            while (i < len && path[i] == '/') i++;
            temp = "";
            while (i < len && path[i] != '/') temp += path[i++];
            if (temp == ".." && !s.empty())
                s.pop();
            else if (temp != "" && temp != "." && temp != "..")
                s.push(temp);
        }
        if (s.empty()) return "/";
        while (!s.empty()) {
            result = "/" + s.top() + result;
            s.pop();
        }
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值