Very Easy to understand C++ code


  • 0
    R
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.size()==0)
            return string();
        if(strs.size()==1)
            return strs[0];
        int k = strs[0].size();
        int j = 0;
        int flag = 0;
        while(j<k){
            for(int i=1;i<strs.size();i++){
                if(strs[i].size()<j+1||strs[i][j]!=strs[i-1][j]){
                    flag = 1;
                    break;
                }
            }
            if(flag == 1)
                break;
            j++;
        }
        return strs[0].substr(0,j);
    }

Log in to reply
 

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