สมมติว่าเรามีรายชื่อโฟลเดอร์ เราต้องลบโฟลเดอร์ย่อยทั้งหมดในโฟลเดอร์เหล่านั้นและส่งคืนโฟลเดอร์ตามลำดับหลังจากลบออก ที่นี่หากโฟลเดอร์[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 และอีกอาร์เรย์หนึ่ง
- สำหรับ i ในช่วง 0 ถึงขนาดของพาธอาร์เรย์ – 1
- s :=path_array[i]
- temp :=สตริงว่าง
- ตั้งค่าสถานะเป็นจริง
- สำหรับ j ในช่วง 0 ถึงขนาดของ s
- อุณหภูมิ :=อุณหภูมิ + s[j]
- เพิ่ม j ขึ้น 1
- ในขณะที่ j <ขนาดของอาร์เรย์และ s[j] ไม่ใช่ '/'
- temp :=temp + s[j] และเพิ่ม j ขึ้น 1
- ถ้า m[temp] ไม่ใช่เท็จ ให้ตั้งค่าสถานะ :=false และแตก
- ถ้าแฟล็กเป็นจริง ให้แทรก s ลงใน ans และตั้งค่า m[s] :=true
- คืนสินค้า
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
ตัวอย่าง
#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, ]