在 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 和另一个数组 ans
- 对于 i 从 0 到路径数组的大小 - 1
- s := path_array[i]
- temp := 空字符串
- 将标志设置为 true
- 对于 j 从 0 到 s 的大小
- temp := temp + s[j]
- j 加 1
- 当 j < 数组大小且 s[j] 不是 ‘/’ 时
- temp := temp + s[j],并且 j 加 1
- 如果 m[temp] 不为 false,则 flag := false,并跳出循环
- 如果 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, ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP