Simple 8ms C++ solution


  • 0
    _
    string longestCommonPrefix(vector<string> &strs) {
        string res="";
        int minp=INT_MAX;
        int n=strs.size();
        if(n==1)
            return strs[0];
        for(int i=0;i<n-1;i++){
            string s1=strs[i];
            string s2=strs[i+1];
            int j=0;
            while(j<s1.size() && j<s2.size()){
                if(s1[j]!=s2[j])
                    break;
                j++;
            }
            if(j<minp){
                minp=j;
                res=s1.substr(0,j);
            }    
        }
        return res;
    }

Log in to reply
 

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