Simple C++ solution 85 ms runtime, beats 89.75%


  • 0
    B

    The idea is simple.

    1. Get the directory path (dir_path).
    2. Get the files(file_path) and their data in directory.
    3. Add the data and dir_path + file_path to an unordered_map<data, vector of absolute path to files>
    4. Go through all the objects in the unordered_map and for objects with vector of absolute path to files > 1 add them to result.

    code:

    #include <unordered_map>
    class Solution {
    private:
        void Parse(std::string file, std::unordered_map<std::string, std::vector<std::string>>& map) {
            std::string path, filenm, data;
            size_t index = 0;
            while(file[index] != ' ') {
                path.push_back(file[index]);
                index++;
            }
            index++;
            bool sw = false;
            while(index < file.length()) {
                if(file[index] == ')') {
                    index += 2;
                    map[data].push_back(filenm);
                    //std::cout << filenm << " : " << data << "\n";
                    filenm.clear();
                    data.clear();
                    sw = false;
                    continue;
                }
                if(file[index] == '(') {
                    index++;
                    filenm = path + '/' + filenm;
                    sw = true;
                    continue;
                }
                if(!sw) {
                    filenm.push_back(file[index]);
                    index++;
                } else {
                    data.push_back(file[index]);
                    index++;
                }
            }
        }
    public:
        vector<vector<string>> findDuplicate(vector<string>& paths) {
            std::unordered_map<std::string, std::vector<std::string>> map;
            std::vector<std::vector<std::string>> res;
            for(std::string path : paths) {
                Parse(path, map);
            }
            
            for(std::pair<std::string, std::vector<std::string>> pr : map) {
                if(pr.second.size() > 1) {
                    res.push_back(pr.second);
                }
            }
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.