71. 简化路径

原题链接:71. 简化路径

 

solution:
        ① 以'/'为分隔符分割字符串,这样就可以提取'/'间有效的内容,保存在items中
        ② 利用栈的性质,遍历items,如果遇到的不是'.'、'..'和空字符串就把内容入栈,如果遇到的是'..'就把栈顶内容弹出。
        ③ 最后保存答案

class Solution {
public:
    string simplifyPath(string path) {
        vector<string> items = split(path, '/');
        string res = "";    //定义返回值
        stack<string> stk;
        for(int i = 0;i < items.size();i++) {
            if(check_true(items[i])) stk.push(items[i]);
            else if(check_back(items[i]) && !stk.empty()) stk.pop();
        }
        if(stk.empty()) res += "/";
        while(!stk.empty()) {
            res.insert(0, stk.top());
            res.insert(0, "/");
            stk.pop();
        }
        return res;
    }   
    //检查是不是有效返回
    bool check_back(const string s) {
        if(s == "..") return true;
        return false;
    }
    
    bool check_true(const string s) {
        if(s != "." && s != ".." && s != "") return true;
        return false;
    }
    //字符串分割
    vector<string> split(const string s, char t) {
        vector<string> items;
        for(int i = 0;i < s.size();i++) {
            int j = i;
            string item;
            while(j < s.size() && s[j] != t) item += s[j++];
            i = j;
            items.push_back(item);
        }
        return items;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值