在C ++中从文件系统中删除子文件夹
假设我们有一个文件夹列表,我们必须删除这些文件夹中的所有子文件夹,并在删除后以任何顺序返回这些文件夹。在这里,如果一个文件夹[i]位于另一个文件夹[j]中,则将其表示为其子文件夹。路径将类似于folder1 / subfolder2 /…等。
假设输入像
["/myfolder","/myfolder/secondfolder","/another/document","/another/document/extrafolder","/another/final"], then the output will be:["/myfolder","/another/final","/another/document"]
为了解决这个问题,我们将遵循以下步骤-
根据路径长度对文件夹数组进行排序
创建一个映射m,然后创建另一个数组
对于范围在0到路径数组大小的i – 1
temp:= temp + s [j]
将j增加1
而j <数组的大小,而s [j]不是'/'
如果m [temp]不为假,则标志:= false,并中断
temp:= temp + s [j],并将j增加1
s:= path_array [i]
temp:=空字符串
将标志设置为true
对于范围在0到s大小之间的j
如果flag为true,则将s插入ans,并设置m [s]:= true
返回ans
让我们看下面的实现以更好地理解-
示例
#include <bits/stdc++.h>using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
static bool cmp(string s,string x){
return s.size()<x.size();
}
vector<string> removeSubfolders(vector<string>& f) {
sort(f.begin(),f.end(),cmp);
map <string,bool> m;
vector <string> ans;
for(int i =0;i<f.size();i++){
string s= f[i];
string temp="";
bool flag = true;
for(int j =0;j<s.size();){
temp+=s[j];
j++;
while(j<s.size() && s[j]!='/'){
temp+=s[j];
j++;
}
if(m[temp]){
flag = false;
break;
}
}
if(flag){
ans.push_back(s);
m[s]=true;
}
}
return ans;
}
};
main(){
vector<string> v = {"/myfolder","/myfolder/secondfolder","/another/document","/another/document/extrafolder","/another/final"};
Solution ob;
print_vector(ob.removeSubfolders(v));
}
输入项
["/myfolder","/myfolder/secondfolder","/another/document","/another/document/extrafolder","/another/final"]
输出结果
[/myfolder, /another/final, /another/document, ]
以上是 在C ++中从文件系统中删除子文件夹 的全部内容, 来源链接: utcz.com/z/331273.html