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

一、 题目描述

在这里插入图片描述

二、解题思路

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

四、运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44587168/article/details/105884790