How good can that be? What can be considered a benchmark?



  • Objective:

    Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string."

    Example:

    Input: strs = ["flower,""flow,"flight."
    Output: "fl."

    My decision is:

    string longestCommonPrefix(vector<string>& strs) 
        {
    
       std::sort(strs.begin(),strs.end(),
        [](const string&amp; a, const string&amp; b)
        { return a.length() &lt; b.length(); });
        
        std::string answer = strs[0];
        if(strs.size() == 0)
            return "";
        std::size_t found;
        for (int i = 1; i &lt; strs.size(); ++i)
        {
            found = strs[i].find(answer);
            if (found != 0)
            {
                answer = answer.substr(0,answer.length()-1);
                i = 0;
                continue;
            }
        }
        
        return answer;
    }
    

    The evaluation of this decision was as follows:
    введите сюда описание изображения In general, it seems pretty good. But would you like to know how good this is?
    Do you have a name? What kind of algorithm is the benchmark for this task?



  • Well, I've got this decision, based on a simple bulk of all the symbols from the first (yes and + some private cases):

    string longestCommonPrefix(vector<string>& strs)
    {
        const int N = strs.size();
        if (N == 0) return "";
        if (N == 1) return strs[0];
        int l = 0;
        string s;
        for(;;++l)
        {
            char c = strs[0][l];
            if (c == 0) return s;
            bool ok = true;
            for(int i = N; i-->1;)
                if (strs[i][l] != c) { ok = false; break;}
            if (!ok) return s; else s += c;
        }
    }
    

    Says

    Runtime: 0 ms, faster than 100.00% of C++ online submissions for Longest Common Prefix.
    Memory Usage: 9.2 MB, less than 77.26% of C+ online submissions for Longest Common Prefix.

    введите сюда описание изображения

    But what's the perfect solution - I don't know. ♪ ♪

    OK, to take off the extra questions. ♪ ♪

    string longestCommonPrefix(vector<string>& strs)
    {
        const int N = strs.size();
        if (N == 0) return "";
        if (N == 1) return strs[0];
        int l = 0;
        string s;
        s.reserve(strs[0].size());
        for(;;++l)
        {
            char c = strs[0][l];
            if (c == 0) return s;
            bool ok = true;
            for(int i = N; i-->1;)
                if (strs[i][l] != c) { ok = false; break;}
            if (!ok) return s; else s.push_back(c);
        }
    }
    

    It's funny that this decision also reduced the number of memory used:

    введите сюда описание изображения



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2