The solution which beats 100.00% cpp coders


  • 1
    B
    class Solution 
    {
    public:
     string longestCommonPrefix(vector<string>& strs)
    {
        string ret;
        if(strs.size()==0){return ret;}
        int maxL=strs[0].size();
        for(int i=1;i<strs.size();i++)
        {
            if(maxL>strs[i].size())
            {
                maxL=strs[i].size();
            }
        }
        for(int i=0;i<maxL;i++)
        {
            char c=strs[0][i];
            for(int j=1;j<strs.size();j++)
            {
                if(c!=strs[j][i])
                {
                    return ret;
                }
            }
            ret.append(1,c); 
        }
        return ret;
    }
    };

  • 0
    T

    That maxL got me for a moment, it's actually the minimum of lengths of strings in strs, or the "maximum possible prefix length".


Log in to reply
 

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