ফোল্ডার পথের একটি লিস্ট দেওয়া থাকলে, যেসব ফোল্ডার অন্য ফোল্ডারের সাব-ফোল্ডার, সেগুলো সরিয়ে বাকিগুলো রিটার্ন করতে হবে।
উদাহরণ: ["/myfolder","/myfolder/secondfolder","/another/document","/another/document/extrafolder","/another/final"] → ["/myfolder","/another/final","/another/document"]।
সমাধানের ধাপসমূহ
- পথগুলো দৈর্ঘ্য অনুযায়ী সাজান (ছোট পথ আগে)।
- একটি ম্যাপ
mরাখুন যেটি প্রসেস করা রুট ফোল্ডারগুলো ট্র্যাক করবে। - প্রতিটি পথের জন্য প্রতিটি কম্পোনেন্ট ( '/' দিয়ে বিভক্ত) চেক করুন যে পেরেন্ট ম্যাপে আছে কিনা।
- নেই তবে আউটপুটে যোগ করুন এবং ম্যাপে যোগ করুন।
C++ উদাহরণ
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<string> v) {
cout << "[";
for (auto& s : v) cout << s << ", ";
cout << "]" << endl;
}
class Solution {
static bool cmp(const string& a, const string& b) {
return a.size() < b.size();
}
public:
vector<string> removeSubfolders(vector<string>& f) {
sort(f.begin(), f.end(), cmp);
unordered_set<string> seen;
vector<string> ans;
for (auto& path : f) {
bool isSub = false;
string cur = "";
for (int i = 0; i < path.size(); ) {
cur += path[i++];
while (i < path.size() && path[i] != '/') cur += path[i++];
if (seen.count(cur)) { isSub = true; break; }
}
if (!isSub) { ans.push_back(path); seen.insert(path); }
}
return ans;
}
};
int 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, ]