LeetCode 71 简化路径

模拟题,根据题目直接设计即可

class Solution {
public:
    string simplifyPath(string path) {
        stack<string> stk;
        string ans;
        string temp;
        //因为程序只有在遇到/时会处理,这里解决/..这样的case
        path = path + "/";

        for(char c : path){
            if(c == '/'){
                //遇到/时说明两个/之间的字符拼接完成,这里进行处理
                if(stk.empty()){
                    //第一个
                    stk.push("/");
                }else{
                    //联续的/
                    if(temp == "" && stk.top() == "/") continue;
                    //处理..
                    if(temp == ".."){
                        if(stk.size() > 1){
                            stk.pop();stk.pop();
                        }
                        
                    }else if(temp != "."){
                        //处理正常的目录
                        stk.push(temp);
                        stk.push("/");  
                    }
                    temp = "";
                }
            }else{
                //拼接两个/直接的字符
                temp.push_back(c);
            }
        }
        //拼接字符串
        while(!stk.empty()){
            ans = stk.top() + ans;
            stk.pop();
        }
        //处理最后多余的/
        if(ans.length() != 1 && ans[ans.length()-1] == '/') ans.pop_back();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值