题目描述
题目分析
题目的意思是每次输入一个路径,可能是绝对的,也可能是相对的,要求我们判断它的种类并将他正则。一共有三种情况:
- 空串,返回当前路径(父路径)
- 第一个字符为不为‘/’,相对路径,加上当前路径后正则
- 第一个字符为为‘/’,绝对路径,直接正则
这道题思路想明白后很简单,但是实现需要一点功夫。通过这道题,我花时间整理了C和C++的流类对象及函数的用法,传送门:
【C 字符串处理】格式化输入输出
【C++】几种流类函数的使用
失分点
- 在使用
getline(cin, op_path);
之前,务必吞掉之前输入的回车!利用一行getchar();
即可搞定; while (ss>>s)
的用法是以空格为分隔符,使用前务必替换‘/’;- 行尾不要多打出‘/’;
- 其他的注释写的非常详细,按需阅读即可。
代码
#define _CRT_SECURE_NO_WARNINGS
#define _ ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#include <bits/stdc++.h>
//#include <iostream>
//#include<algorithm>
using namespace std;
int main()
{
int P;//需要进行正规化操作的路径个数
string cur_path;//当前目录
cin >> P >> cur_path;
getchar();//吞回车
while (P--)
{
string op_path;//待操作路径
getline(cin, op_path);//用getline可以读空格,即防止路径中出现空格
if (op_path == "") op_path = cur_path;//若路径为空字符串,则正规化操作的结果是当前目录
if (op_path[0] != '/')op_path = cur_path + '/' + op_path;//待处理的相对路径
for (int i = 0; i < op_path.size(); i++)
{
if (op_path[i] == '/')op_path[i] = ' ';//替换为空格以便stringstream流操作
}
vector<string> segment_path;//用于存储输出路径段
stringstream ss(op_path);
string s;
while (ss>>s)//名场面
{
if (s == ".")continue;
else if (s == ".." && segment_path.empty())continue;
else if (s == ".." && !segment_path.empty())segment_path.pop_back();
else segment_path.push_back(s);
}
cout << '/';
for (int i = 0; i < segment_path.size(); i++)
{
if (i == 0)cout << segment_path[i];
else cout << '/' << segment_path[i];
}
cout << endl;
}
return 0;
}