C++ without explicit loops (uses the sort trick)


  • 0
    M
        class Solution {
        public:
            string longestCommonPrefix(vector<string>& strs)
            {
                if (strs.empty()) return{};
    
                sort(begin(strs), end(strs));
    
                auto diffs = mismatch(
                    begin(strs.front()), end(strs.front()),
                    begin(strs.back()));
    
                auto len = min(
                    distance(begin(strs.front()), diffs.first),
                    distance(begin(strs.back()), diffs.second));
    
                return strs[0].substr(0, len);
            }
        };
    

Log in to reply
 

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