6ms C++ Solution (15 lines)


  • 0
    A
    string longestCommonPrefix(vector<string>& strs) {
            string pf="";    
            int sl=0;
            if(strs.size()<=0) return pf;
            while(1){
                if(strs[0].size()<=sl) return pf;
                for(int i=1;i<strs.size();i++){
                    if(strs[i].size()<=sl) return pf;
                    if(strs[i][sl]!=strs[0][sl]) return pf;
                }
                pf.push_back(strs[0][sl]);
                sl++;
            }
            return pf;
        }
    

Log in to reply
 

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