Clean 7 lines C++


  • 0

    Solution 1

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if(strs.empty()) return "";
            string res = strs[0];
            for(auto s: strs) res = match(res, s);
            return res;
        }
        
        string match(const string& pre, const string& s){
            int i = 0, len = min(pre.size(), s.size());
            for(; i < len; i++) if(s[i] != pre[i]) break;
            return pre.substr(0, i);
        }
    };
    

    Solution 2

    Using sort and only compare the first string with the last string.

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if(strs.empty()) return "";
            sort(strs.begin(), strs.end());
            string a = strs[0], b = strs.back();
            int i = 0;
            for(; i < min(a.size(), b.size()); i++) if(a[i] != b[i]) break;
            return a.substr(0, i);
        }
    };
    

Log in to reply
 

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