Unix路径简化(模拟题) - 搜狐集团2018秋季校招笔试题二(技术类)

时间限制:C/C++ 1秒;其他语言 2秒
内存限制:C/C++ 32768KB;其他语言 65536KB

题目描述:
简化Unix风格的路径,需要考虑的包括“/../”,”//”,“/./”等情况

输入描述
Unix风格的路径

输出
简化后的Unix风格路径

样例输入
/a/./b/../../c/
样例输出
/c

解题思路:纯模拟

  • “/.” 表示本级目录,可以忽略
  • “/..” 表示返回上一级目录,即若上一级目录存在,连同“/..”一并删除,否则只删除“/..”
  • 若去除冗余后路径为空,返回“/”
  • 若包含多个连续“/”, 删除多余的“/”
#include <iostream>
#include <string>
#include <list>
using namespace std;

int main()
{
    string str;
    list<string> path;
    while(cin >> str)
    {
        path.clear();
        for(int i = 0; i < str.length(); ++i)
        {
            if(str[i]=='/')
            {
                i++;
                string tmp = "";
                while(str[i]!='/' && i < str.length())
                    tmp+=str[i++];
                i--;
                if(tmp=="..")
                {
                    if(!path.empty())
                        path.pop_back();
                }
                else if(tmp!="." && tmp!="")
                    path.push_back(tmp);
            }
        }
        if(path.empty())
            cout << "/";
        while(!path.empty())
        {
            cout << "/" << path.front();
            path.pop_front();
        }
        cout << endl;
    }
    return 0;
}
/*
/a/./b/../../c/
/home/
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值