leetcode 71: Simplify Path

So fucked up by all detailed corner cases!!!

class Solution {
public:
    string simplifyPath(string path) {
        string res;
        res+=path[0];
        int dot_num=0;
        for(int i=1;i<path.size();i++)
        {
            if(path[i]=='/')
            {
                if(path[i-1]>='a'&&path[i-1]<='z')
                    res+=path[i];
                else if(dot_num==1&&path[i-1]=='.')
                    res.pop_back();
                else if(dot_num==2&&res.size()!=3&&path[i-1]=='.')
                {
                    for(int j=0;j<3;j++)
                        res.pop_back();
                    while(res[res.size()-1]!='/')
                        res.pop_back();
                }
                else if(dot_num==2&&res.size()==3)
                {
                    res.pop_back();
                    res.pop_back();
                }
                else if(path[i-1]=='/')
                    continue;
                else
                {
                    res+='/';
                }
                dot_num=0;
            }
            else if(path[i]=='.')
            {
                res+='.';
                dot_num++;
            }
            else
                res+=path[i];
        }
        if(res[res.size()-1]=='.')
        {
            if(dot_num==2&&res.size()!=3)
            {
                for(int i=0;i<3;i++)
                    res.pop_back();
                while(res[res.size()-1]!='/')
                    res.pop_back();
            }
            else if(dot_num==2&&res.size()==3)
            {
                res.pop_back();
                res.pop_back();
            }
            else if(dot_num==1)
                res.pop_back();
        }
        while(res[res.size()-1]=='/'&&res.size()>1)
            res.pop_back();
        return res;
    }
};

Updated version, looks cleaner

class Solution {
public:
    string simplifyPath(string path) {
        vector<string> dir;
        int i=0,j=1;
        int len=path.length();
        if(path[len-1]!='/')//add a / at the end if there is no
        {
            path.push_back('/');
            len++;
        }
        while(j<len)
        {
            if(path[j]=='/')
            {
                string temp=path.substr(i,j-i);
                if(temp=="/.."&&!dir.empty())//delete previous directory
                    dir.pop_back();
                else if(temp!="/"&&temp!="/."&&temp!="/..")
                    dir.push_back(temp);
                i=j;
            }
            j++;
        }
        if(dir.empty())
            return "/";
        string res;
        for(int i=0;i<dir.size();i++)
            res+=dir[i];
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值