题意介绍
给出一系列文件路径,输出正规化后的路径。
题意分析
有分析可知,给出的路径只有两种形式,一是绝对路径(以‘/’开头),二是相对路径(以‘.’开头),对于相对路径的处理,可以将它与当前目录连在一起,变成绝对路径后再正规化,根据分析得出将一个路径(绝对路径)正规化要考虑到以下四点:
路径中是否出现“///”;
路径中是否出现“/…/”;
路径中是否出现“/./”;
路径的最后是否为“/”;
还有一点就是题目输入可能给一个空的路径,这时候输出当前目录即可。
通过代码
#include<iostream>
#include<string>
using namespace std;
int p,pos;
string cur;
int main() {
cin >> p;
cin >> cur;
getchar();
for (int i = 0; i < p; i++) {
string s;
getline(cin, s);
if (s[0] != '/') s = cur + "/" + s;
if (s.size() == 0) s = cur;
//去除///
while ((pos = s.find("//"))!=-1) {
int count = 2;
while (s[pos + count] == '/') count++;
s.erase(pos, count - 1);
}
//去除/../
while ((pos = s.find("/../"))!=-1) {
int count = 3;
if (pos != 0) {
count = 4;
while (pos - 1 >= 0 && s[pos-1] != '/') {
count++;
pos--;
}
}
s.erase(pos, count);
}
//去除/./
while ((pos = s.find("/./"))!=-1) {
s.erase(pos, 2);
}
//去除最后一个/
if (s.size() > 1 && s[s.size() - 1] == '/')
s[s.size() - 1] = '\0';
cout << s << endl;
}
return 0;
}