题解 | #路径打印#
路径打印
https://www.nowcoder.com/practice/64b472c9bed247b586859978d13145ad
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 11;
vector<string> vec[N];
string str;
int n;
int main(){
while(cin >> n && n != 0){
for (int i = 0; i < n; i ++) {
vec[i].clear();
cin >> str;
string temp;
for(int j = 0; j < str.size(); j ++){//将每个路径拆分到一个vec[i]中
while (j < str.size() && str[j] != '\\') {
temp += str[j ++];
}
vec[i].push_back(temp);
temp.clear();
}
}
sort(vec, vec + n); //对n个路径,按第一个结点的首字母排序
for(int i = 0; i < n; i ++){
if (i == 0) {//第一个路径直接输出
for (int j = 0; j < vec[i].size(); j ++) {
for (int k = 0; k < j; k ++) {//每个结点前的空格数
cout << " ";
}
cout << vec[i][j] << endl;
}
}else{//后面的路径需要判断其与上一个路径相同的父目录
int k = 0;//记录相同的父目录下标
while(k < vec[i].size() && k < vec[i - 1].size() && vec[i][k] == vec[i - 1][k])
k ++;
for (int j = k; j < vec[i].size(); j ++) {
for(int l = 0; l < j; l ++)
cout << " ";
cout << vec[i][j] << endl;
}
}
}
cout << endl;//每一个测试样例的输出都多一个空行
}
return 0;
}
海康威视公司氛围 920人发布