LeetCode-609: 在系统中查找重复文件

14 篇文章 0 订阅
11 篇文章 0 订阅

一、 题目描述

在这里插入图片描述

二、解题思路

使用哈希表来实现。首先提取字符串中的内容,形成 k e y = C o n t e n t , v a l u e = P a t h key = Content, value = Path key=Content,value=Path p a i r pair pair。之后建立一个 k e y key key s t r i n g string string类、 v a l u e value value v e c t o r < v e c t o r < s t r i n g > > vector<vector<string>> vector<vector<string>>类型的 u n o r d e r e d unordered unordered_ m a p map map。之所以采用 u n o r d e r e d unordered unordered_ m a p map map是因为其内部实现为哈希表。遍历一遍 v e c t o r < s t r i n g > p a t h s vector<string> paths vector<string>paths,在创造 p a i r pair pair的过程中查看在 u n o r d e r e d unordered unordered _ m a p map map里是否存在与 k e y = C o n t e n t key = Content key=Content相等的 p a i r pair pair,如果有,就把当前这个 p a i r pair pair v a l u e = s t r i n g value = string value=string插入到这个值对应的 v e c t o r < s t r i n g > vector<string> vector<string>里。

三、解题代码

class Solution {
private:
    pair<string, string> CreateDocPair(string str, string rootPath){
        int prior = 0;
        for(; prior < str.size() && str[prior] != '('; prior++);
        auto Name = rootPath + "/" + str.substr(0, prior);
        auto Content = str.substr(prior + 1, str.size() - 1 - (prior + 1));
        return make_pair(Content, Name);
    }
public:
    vector<vector<string>> findDuplicate(vector<string>& paths) {
        unordered_map<string, vector<string>> mp;
        vector<pair<string, string>> doc;
        for(int i = 0; i < paths.size(); i++)
        {
            auto tmpCMD = paths[i];
            int prior = 0;
            for(; prior < tmpCMD.size() && tmpCMD[prior] != ' '; prior++);
            auto rootPath = tmpCMD.substr(0, prior++);
            for(; prior < tmpCMD.size(); prior++){
                int ahead = prior;
                for(; ahead < tmpCMD.size() && tmpCMD[ahead] != ' '; ahead++);
                auto ret = CreateDocPair(tmpCMD.substr(prior, ahead - prior), rootPath);
                prior = ahead;
                mp[ret.first].push_back(ret.second);
            }
        }
        vector<vector<string>> sln;
        for(auto it: mp)
            if(it.second.size() > 1)   sln.push_back(it.second);
        return sln;
    }
};

四、运行结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值