LC.71 | 简化路径 | 栈 | 字符栈模拟/字符串分割

输入:一个字符串 path,它是一个 Unix 风格的绝对路径。

要求:将给定的绝对路径转换为简化的“规范路径”。规范路径需遵循:

  • 始终以一个 / 开头。

  • 两个目录名之间有且只有一个 /

  • 路径不能以 / 结尾(除非是 /)。

  • . (当前目录) 应被忽略。

  • .. (上一级目录) 应移除上一级目录。

  • 连续的 // 应被视为一个 /

输出:一个字符串,表示简化后的规范路径。


思路1:使用字符栈模拟。遍历路径字符串,以字节为单位进行处理。

复杂度:

        时间复杂度:O(n)

        空间复杂度:O(n)


 class Solution {
public:
    string simplifyPath(string path) {
        string s = path + "/";
        int len = s.size();
        stack<char> tmp;
        for (int i = 0; i < len; i++) {
            if (s[i] != '/') {
                tmp.push(s[i]);
            }
            else {
                if (tmp.empty()) {
                    tmp.push(s[i]);
                }
                else if (tmp.top() == '.') {
                    if (s[i-2] == '/') {
                        tmp.pop();
                    }
                    else if (s[i-2] == '.' && s[i-3] == '/') {
                        tmp.pop();
                        tmp.pop();
                        if (tmp.size() == 1) {
                            continue;
                        }
                        tmp.pop();
                        while (tmp.top() != '/') {
                            tmp.pop();
                        }
                    }
                    else {
                        tmp.push(s[i]);
                    }
                }
                else if (tmp.top() == '/') {
                    //无视此项
                }
                else {
                    tmp.push(s[i]);
                }
            } 
        }
        if (tmp.top() == '/' && tmp.size() > 1) {
            tmp.pop();
        }
        string ans;
        while (!tmp.empty()) {
            ans += tmp.top();
            tmp.pop();
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

思路2:先将字符串分割,然后再进行处理,以字符串为单位进行处理。

复杂度:

        时间复杂度:O(n)

        空间复杂度:O(n)

class Solution {
public:
    string simplifyPath(string path) {
        vector<string> dirs; // 用 vector 模拟栈
        stringstream ss(path);
        string component;

        // 按 '/' 分割字符串
        while (getline(ss, component, '/')) {
            if (component.empty() || component == ".") {
                continue;
            } 
            else if (component == "..") {
                if (!dirs.empty()) {
                    dirs.pop_back();
                }
            }
            else {
                dirs.push_back(component);
            }
        }

        // 将栈中的有效目录拼接成最终路径
        if (dirs.empty()) {
            return "/";
        }

        string ans;
        for (const string& dir : dirs) {
            ans += "/" + dir;
        }
        
        return ans;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值