Easy to understand c++ code 4ms

  • 1

    // assume the first string is common, and gradually shorten the common when comparing with the other strings

        int len = strs.size();
        if(len==0) return "";
        if(len==1) return strs[0];
        string common = strs[0];
        if(common.empty()) return "";
        for(int i=1; i<len; ++i) {
            string str2 = strs[i];
            if(str2.empty()) return "";
            int num = min(common.size(), str2.size());
            for(int j=0; j<num; ++j) {
                if(common[j]!=str2[j]) {
                    common = common.substr(0, j);
                common = str2;
        return common;

Log in to reply

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