C++ easy solution


  • 0
    B
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.size()>0)
            if(strs.size()==1)
                return strs[0];
            else
                ;
        else
            return "";
        for(int i=0;;i++){
            for(int j=0;j<strs.size()-1;j++)
                if(i<strs[j].size()&&strs[j][i]==strs[j+1][i])
                    ;
                else
                    return strs[0].substr(0,i);
        }
        return strs[0];
    }

  • 0
    Y

    what if i > strs[j+1].size()? which will cause index out of bound for the following code:
    strs[j][i]==strs[j+1][i]


Log in to reply
 

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