实现
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
void handle_path(vector<string>& paths, string path) {
stringstream ss(path);
string dir;
bool first_dir = true;
while (getline(ss, dir, '/')) {
if (dir.empty()) {
if (first_dir) {
paths = vector<string> ();
}
} else if (dir == ".."){
if (!paths.empty()) {
paths.pop_back();
}
} else if (dir == ".") {
// pass
} else {
paths.push_back(dir);
}
first_dir = false;
}
}
void print_formalized_path(vector<string> paths) {
if (paths.empty()) {
cout << "/" << endl;
return;
}
for (vector<string>::iterator ite = paths.begin();
ite!=paths.end();++ite) {
cout << "/" << *ite;
}
cout << endl;
}
int main() {
int num;
cin >> num;
cin.ignore();
string cur_path;
getline(cin,cur_path);
vector<string> cur_paths, paths;
handle_path(cur_paths, cur_path);
for (int i = 0;i < num;++i) {
string path;
getline(cin,path);
paths = cur_paths;
handle_path(paths, path);
print_formalized_path(paths);
}
}
参考
Pretty9