Find Duplicate File in System

来源:互联网 发布:办公软件培训班多少钱 编辑:程序博客网 时间:2024/05/19 14:55

该题是leetcode中有关string操作的一道题目:

用到的了string中的substr(),find_first_of()等操作


Given a list of directory info including directory path, and all the files with contents in this directory, you need to find out all the groups of duplicate files in the file system in terms of their paths.

A group of duplicate files consists of at least two files that have exactly the same content.

A single directory info string in the input list has the following format:

"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"

It means there are n files (f1.txtf2.txt ... fn.txt with content f1_contentf2_content ... fn_content, respectively) in directory root/d1/d2/.../dm. Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.

The output is a list of group of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:

"directory_path/file_name.txt"

Example 1:

Input:["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"]Output:  [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]
#include <iostream>#include <stdlib.h>#include <stdio.h>#include <vector>#include <string>#include <sstream>#include <map>using namespace std;vector<vector<string> >findDuplicate(vector<string>& paths);int main(){    vector<string> paths;    vector<vector<string> >res;    string s[]={"root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"};    for(int i=0; i<4; i++)    {        paths.push_back(s[i]);    }    res = findDuplicate(paths);    for(int i=0; i<res.size(); i++)    {        for(int j=0; j<res[i].size(); j++)            cout<<res[i][j]<<endl;    }    return 0;}vector<vector<string> >findDuplicate(vector<string>& paths){    vector<vector<string> >res;    vector<string> tmp;    map<string,vector<string> > m;    map<string,vector<string> >::iterator mit;    string filename;    string filepath;    string filecontent;    stringstream ss;    int flag;    for(int i=0; i<paths.size(); i++)    {        flag=0;        ss.clear();        ss.str(paths[i]);        while(!ss.eof())        {            if(flag==0)            {                getline(ss,filepath,' ');                flag=1;            }            else            {                getline(ss,filename,' ');                int pos=filename.find_first_of('(');                filecontent=filename.substr(pos,filename.size()-pos);                filename=filename.substr(0,pos);                m[filecontent].push_back(filepath+"/"+filename);            }        }    }  for(mit=m.begin(); mit!=m.end(); mit++)  {      if(mit->second.size()>1)   res.push_back(mit->second);  }    return res;}



原创粉丝点击