0
点赞
收藏
分享

微信扫一扫

leetCode71. 简化路径

潇湘落木life 2024-05-05 阅读 7

leetCode71. 简化路径
代码

// 化简:就是把所有的., .. // 去掉弄成进入想进的目录,且结果最后不能有/
// 实现思路: 本质上是一个栈,就是进栈出栈的一个模拟实现
class Solution {
public:
    string simplifyPath(string path) {
        // 为了格式统一,都是通过文件名+'/' 进行扫描,在结尾加上一个'/'
        // 为的是每个文件名由'/'截指
        if(path.back() != '/') path += '/'; 

        string res = "", name = "";
        for(auto c : path){
            if(c != '/') name += c;
            else{ 
                // c == '/'后,判断name,①name=="."或者""直接忽略,②name==".."去除前面已经存在的/name
                // c == '/'而name什么都没有,就表示/或者// 直接忽略就好
                if(name == ".."){
                    while(res.size() && res.back() != '/') res.pop_back();
                    if(res.size()) res.pop_back(); // 这个是为了去除name前面的'/'
                }else if(name != "." && name != ""){
                    res += '/' + name;
                }
                name.clear();
            }
        }

        if(res == "") res += '/';
        return res;
    }
};

精简版

class Solution {
public:
    string simplifyPath(string path) {
        if(path.back() != '/') path += '/';

        string res = "", name = "";
        for(auto c : path){
            if(c != '/') name += c;
            else{
                if(name == ".."){
                    while(res.size() && res.back() != '/') res.pop_back();
                    if(res.size()) res.pop_back();
                }else if(name != "." && name != ""){
                    res += '/' + name;
                }

                name.clear();
            }
        }
        if(res.empty()) res += '/';
        return res;
    }
};
举报

相关推荐

0 条评论