LeetCode 1233. 删除子文件夹***

具体思路:

字典树,但是自己以前接触的事固定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;
    }

};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值