4ms c++ solution


  • 2
    C

    string longestCommonPrefix(vector<string>& strs) {
    if (strs.size()==0) return "";

    int len=strs[0].size();
    int i,j;
    for (i=1; i<strs.size();i++){
        for (j=0; j<len;j++){
            if (strs[i-1][j]!=strs[i][j]){
                if (j<len) 
                    len=j;
                break;
            }
        }
    }
    return strs[0].substr(0,len);
    

    }


  • 0
    B

    if (strs[i-1][j]!=strs[i][j]){

    won't you be over boundary here? when j > strs[i].size()


  • 0
    C

    for the vector, the operator [] does not do boubdary checking.


  • 0
    B

    that's true, but this is dangerous, I think


  • 0
    J

    I had the same concern. Then I found online that
    In C++11 and later, mystring.c_str() is equivalent to mystring.data() is equivalent to &mystring[0], and mystring[mystring.size()] is guaranteed to be '\0'


Log in to reply
 

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