在 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, ]

更新於: 2020年4月30日

183 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.