4ms c++ solution


  • 0
    J
    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if(strs.empty()) {
                return "";
            }
            string result = strs[0];
            int vec_size = strs.size();
            
            for (int i = 1; i < vec_size; ++i) {
                string temp = strs[i];
                int str_size = temp.size();
                
                // If string size smaller than actual result size, we
                // trim it down to smaller size first, then do the 
                // comparision.
                if (str_size < result.size()) {
                    result.erase(str_size, result.size() - str_size);
                }
                for (int j = 0; j < str_size; ++j) {
                    if (temp[j] != result[j]) {
                        //trim down to current.
                        result.erase(j, result.size() - j);
                        break;
                    }
                }
            }
            
            return result;
        }
    };

  • 0
    I

    mine 4ms easy to understand solution

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if(strs.size()==0)
                return "";
            if(strs.size()==1)
                return strs[0];
            string prefix = strs[0];
            for(int i = 1;i<strs.size();i++){
                prefix = longestCommonPrefixBetweenTwo(prefix,strs[i]);
                if(prefix=="")
                    return prefix;
            }
            return prefix;
        }
        string longestCommonPrefixBetweenTwo(string &s, string &r){
            if((s.size()==0)||(r.size()==0))
                return "";
            int l1 = s.size(), l2 = r.size(), i = 0;
            for(;i<min(l1,l2);i++){
                if(s[i]==r[i])
                    continue;
                else
                    break;
            }
            return string(s.begin(),s.begin()+i);
        }
    };

Log in to reply
 

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