思路
- 首先对路径进行预处理:若不是绝对路径,将当前地址加到该路径之前;若为空路径或绝对路径则不做处理;然后将所有的‘/’替换成空格,利用
stringstream
对路径进行分割 - 依次读入路径,将结果储存到sta数组中,若遇到“.”,则continue;若遇到“…”且当前数组不为空时,删掉数组中的最后一个元素(也就是返回上一级目录);若两者都不是,直接储存到数组即可
- 数组中存放的即为答案
记得开始要加‘/’
总结
- stringstream太好用了!!!
- 注意审题,输入样例没有空路径不代表测试数据里没有啊!
80分的原因 - 注意空路径的读入,不能使用cin读入,使用getline读入
- cin读入后,注意换行符的吸收
实现代码
#include <vector>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int n;
cin >> n;
string path, s, str;
cin >> path;
cin.get(); //吸收换行符
for (int i = 0; i < n; i++)
{
getline(cin, str);
if (str == "") str = path;
if (str[0] != '/') str = path + '/' + str;
for (int j = 0; j < str.size(); j++)
{
if (str[j] == '/') str[j] = ' ';
}
vector<string> sta;
stringstream ss(str);
while (ss >> s)
{
if (s == ".") continue;
else if (s == ".." && !sta.empty()) sta.pop_back();
else if (s != "..") sta.push_back(s);
}
cout << '/';
for (int j = 0; j < sta.size(); j++)
{
if (j) cout << '/';
cout << sta[j];
}
cout << endl;
}
}