具体思路:
字典树,但是自己以前接触的事固定26个字符的,没想到map也可以构建字典树;
建树时候如果发现路径上已经有终止节点了,直接跳过该字符串;
具体代码:
struct node{
unordered_map<string,node*>dic;
bool isend=false;
string path="";
void insert(vector<string>& vec,string s){
node* root=this;
for(auto& str:vec){
if(root->dic.find(str)==root->dic.end()){
root->dic[str]=new node();
}
root=root->dic[str];
if(root->isend)
return;
}
root->isend=true;
root->path=s;
}
};
class Solution {
public:
vector<string> split(string folder){
istringstream ss(folder);
vector<string>ret;
string temp;
int start=1;
for(int i=start;i<folder.size();i++){
if(folder[i]=='/'){
ret.push_back(folder.substr(start,i-start));
start=i+1;
}
}
ret.push_back(folder.substr(start,int(folder.size())-start));
return ret;
}
void dfs(vector<string>& ret,node* root){
if(root->isend){
ret.push_back(root->path);
return;
}
for(auto it=root->dic.begin();it!=root->dic.end();it++){
dfs(ret,it->second);
}
}
vector<string> removeSubfolders(vector<string>& folder) {
vector<string>ret;
node* root=new node();
for(auto& str:folder){
vector<string>vec=split(str);
root->insert(vec, str);
}
dfs(ret,root);
return ret;
}
};