My 8ms c++ solution


  • 0
    W
    class Solution {
    public:
        string longestCommonPrefix(vector<string> &strs) {
            string comm="";
            int len=strs.size();
            if(len==0)
                return "";
            else
            {
                int p,pmin;
                pmin=strs[0].size();
                for(int i=1;i<len;++i)
                {
                    p=0;
                    while(strs[0][p]==strs[i][p]&&p<pmin)
                        p++;
                    pmin=p;    //number of the letters in the prefix 
                }
                int i=0;
                //construct the prefix
                while(pmin>0)
                {
                    comm=comm+strs[0][i];
                    i++;
                    pmin--;
                }
                return comm;
            }
        }
    };

Log in to reply
 

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