C++ 6ms solution


  • 0
    Z
    class Solution {
    public:
     string longestCommonPrefix(vector<string>& strs) {
            if (strs.empty()) {
               return "";
            }
            nth_element(strs.begin(),strs.begin(),strs.end(),[](string& a,string& b){
                return a.length() < b.length();
            });
            string commen_prefix(*(strs.begin()));
            for (auto && str : strs) {
                if (commen_prefix.empty()) {
                    return  commen_prefix;
                }
                commentPrefix(commen_prefix,str);
            }
            return commen_prefix;
        }
    
    private:
        void commentPrefix(string& commen,const string& str) {
            for (int i = 0; i < commen.size(); ++i) {
                if (commen[i] == str[i]) {
                    continue;
                }
                commen = commen.substr(0,i);
                return;
            }
        }
    };
    

Log in to reply
 

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