8 ms c++ solution with simple comments


  • 0
    D
    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            string ithStr,baseStr;
            if(strs.size() == 0)
                return string();
            int k=0,i=0;
            while(true){
                baseStr=strs.at(0);
                if( k>=baseStr.size())
                    return baseStr.substr(0,k);
        	    for(i=1;i<strs.size();i++){ // check the kth character for all strs in vector 
                    ithStr=strs[i];
                    if(k>=ithStr.size())
                        return baseStr.substr(0,k);
                    else {
                        if(ithStr.at(k)!=baseStr.at(k))
                             return baseStr.substr(0,k);
                    }
                }//for
            k++; // to next character  
    	    }//while        
        }
    };

Log in to reply
 

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