[C++] Clean Code


  • 0
    class Solution {
    public:
        vector<vector<string>> findDuplicate(vector<string>& paths) {
            vector<vector<string>> res;
            map<string, vector<string>> files;
            for (string s : paths) {
                std::istringstream ss(s);
                vector<string> toks{ istream_iterator<string>{ss}, istream_iterator<string>{} };
                string path = toks[0];
                for (int i = 1; i < toks.size(); i++) {
                    int pos = toks[i].find('(');
                    string file = toks[i].substr(0, pos);
                    string content = toks[i].substr(pos + 1, toks[i].size() - 2 - pos);
                    files[content].push_back(path + "/" + file);
                }
            }
    
            for (auto p : files) {
                if (p.second.size() > 1) {
                    res.push_back(p.second);
                }
            }
            return res;
        }
    };
    

  • 1
    J

    The subtle issue is that string object is copied multiple times which makes it 10 time slower than optimal one according to leetcode submission result. It may be better to use string_view, but it's in C++ 17 standard. No offense, just point out the optimization potential.


  • 0
    S

    @alexander said in [C++] Clean Code:

    vector<string> toks{ istream_iterator<string>{ss}, istream_iterator<string>{} };

    Could you please explain the meaning of
    "vector<string> toks{ istream_iterator<string>{ss}, istream_iterator<string>{} };" ?
    Why does toks have the contents of the whole string?
    Thanks.


  • 0

    @shenghsi This is to tokenize the string split by space.


Log in to reply
 

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